I have the following fiddle for this question: http://jsfiddle.net/jcb9xm44/
There are 2 inline-block div's in a parent div:
<div class="outer">
<div class="inner1">
Y
</div>
<div class="inner2">
X
</div>
</div>
The css assigns a width to the parent div and 2 widths to the child div's.
.outer {
width: 210px;
border: 1px solid red;
}
.inner1 {
width: 200px;
border: 1px solid orange;
display: inline-block;
}
.inner2 {
width: 50px;
position:relative;
left: -50x;
display: inline-block;
border: 1px solid lightblue;}
I was expecting that both divs appear on the same line. Although the parent is not wide enough to hold both children, since the second child has a negative offset, it should be possible to fit them both on the same line. Why does it break the line?
If you want to prevent them from wrapping, either remove the white space you have used for formatting, or add white-space:nowrap; to the rule for .
First set position of the parent DIV to relative (specifying the offset, i.e. left , top etc. is not necessary) and then apply position: absolute to the child DIV with the offset you want. It's simple and should do the trick well.
Yes. You will not be able to work with absolutely positioned elements any more, for example - the absolute positioning will always be relative to the parent element, which is almost never the desired result.
Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.
Why does it break the line?
As you stated, it's because the parent element isn't wide enough for both elements. To change this behavior, you could add white-space: nowrap
to the parent element in order to prevent the inline-block
elements from wrapping.
Example Here
.outer {
width: 210px;
border: 1px solid red;
position:relative;
white-space: nowrap;
}
Side notes:
left: -50x
-> left: -50px
.inline
elements respect whitespace in the markup.box-sizing: border-box
to include it.margin-left: -50px
as Mary Melody pointed out.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With