Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does big negative margin-right make absolute element no wrap?

Tags:

css

Update:

The position value will change the width.

The JSFiddle: http://jsfiddle.net/caicai/mbtb5m7p/2/


Why does the width of div .a2 equal to its parent's width, while the the text in the div .a1 won't wrap?

The JSFiddle: http://jsfiddle.net/caicai/mbtb5m7p/

.r {
    position: relative;
    width: 100px;
    height: 22px;
    background: blue;
}
.a1 {
    position: absolute;
    top: 30px;
    margin-right: -9999px;
    background: green;
}
.a2 {
    position: absolute;
    top: 60px;
    background: orange;
}
<div class="r">
    <div class="a1"> 
        Why does this line no wrap. 
    </div>
    <div class="a2"> 
        Why does this line wrap. 
    </div>
</div>
like image 720
Zhiyong Cai Avatar asked May 19 '15 13:05

Zhiyong Cai


2 Answers

The div.r has a width of 100px and is placed relative.

The children .a1 and .a2 are placed absolute. The related on their (relatively placed) parent.

Without a negative margin, the children will take a maximum width equal to its parents size.

But, by adding a negative margin, you allow the children to "float over" its parents borders.

like image 171
LinkinTED Avatar answered Oct 19 '22 20:10

LinkinTED


It's not that the content of .a1 is no longer wrapping, it is that the content of .a1 has no need to wrap because the available interior space has been made wide enough for the string inside it by your negative margin.

So your div.a1 will essentially be the width of .r + the value of the negative margin, which is dragging out the right extremity and increasing the size of your div.

That's pretty much how the box model works, check it out here or here

like image 2
BenLeah Avatar answered Oct 19 '22 19:10

BenLeah