Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css relative positioning breaks div into new line

Tags:

html

css

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?

like image 532
shaft Avatar asked Oct 12 '14 23:10

shaft


People also ask

How do I keep my div from wrapping to the next 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 .

How do you make a div position relative to another div?

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.

Is it bad to use position relative in CSS?

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.

Can a div be position absolute and relative?

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.


1 Answers

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:

  • You had a typo - left: -50x -> left: -50px.
  • inline elements respect whitespace in the markup.
  • The element's border is included in its width calculations. Use box-sizing: border-box to include it.
  • You could alternatively use margin-left: -50px as Mary Melody pointed out.
like image 176
Josh Crozier Avatar answered Sep 30 '22 13:09

Josh Crozier