css3定位问题根目录百分百宽度

    <style>
        .a {
            margin: 100px auto;
            width: 300px;
            height: 300px;
            background-color: red;
        }

        .b {

            position: absolute;
            width: 100%;
            height: 50px;
            background-color: green;
        }
    style>
head>

<body>

    <div class="a">
        <div class="b">div>
    div>

body>

img


他的100%是根目录的大小 ,
想问为什么.b左边没有拉长。

position:absolute设置的元素,其绝对位置相对的元素是它最近的一个父级元素,偏移值由此元素的top、buttom、left、right确定,所以只需要在样式b中添加left:0;即可。望采纳,谢谢

img

img

.a 加个相对定位


.a {
      margin: 100px auto;
      width: 300px;
      height: 300px;
      background-color: red;
      position: relative;
  }

  .b {

      position: absolute;
      width: 100%;
      height: 50px;
      background-color: green;
  }

你 .a相对定位 .b绝对定位 。
所以 .b是相对于 .a 定位 。并不是根元素 。 这个叫父相子绝 。挺常用的 。也就是 相对于 父元素定位

absolute原因