简体   繁体   中英

Which ancestor is a relatively positioned element positioned relative to?

When a CSS element with relative position is positioned 50% to the left, what is it relative too? I would have thought that it was to the nearest parent element, but that doesn't seem to be the case in the following:

HTML

<div class="line">
    <span>
        <span>1234451</span>
    </span>
</div>

CSS

.line {
    width: 1px;
    position: fixed;
    height: 100%;
    left: 50%;
    border-left: 1px solid red;
}

.line span {
    position: relative;
}

.line span span {
    position: relative;
    left: -50%;
    border: 1px solid black;
    background-color: grey;
}

This results in the numbers left side starting at the line, like so:

           1234451
          |
          |
          |

If I change the width of the.line element to auto though, I get the desired outcome:

       1234451
          |
          |
          |

It seems that the positioning of the innermost element is not relative to its parent, but to its grandparent. Is that correct? And if so why?

This is happening because you don't understand how spans work. The innermost span is relative to its parent always.

What happens in your two examples is that in the first example, the width of your outer span is 1px because you limited its size to that when you told the div to be 1px wide. So the innermost span is moving 50% to the left, relative to the parent span's 1px of width.

In the second example, you let the div's width size itself. It became as large as it needs to be to encompass the content in the innermost div. The outer span then also became this same width, which is also the width of the innermost span, because the content of the innermost span is what is deciding the width of all three elements. Therefore, now, the innermost span is moving 50% to the left, relative the the parent span's width, which is equal to the width of the div, which is equal to the width of the content inside of the innermost span.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM