0

Inline <li> elements are not positioning themselves within their parent div. It is ok when I set overflow:auto on the parent div but not without it.

Please help me understand it, how they are getting out of their parent.

Here is my code:

body {
  margin: 0;
  padding: 0;
}

div {
  background-color: black;
  color: red;
  padding-top: 2px;
  padding-bottom: 2px;
}

li {
  display: inline;
  float: right;
}

ul {
  list-style-type: none;
}
<h1>BUSINESS NAME</h1>

<div>
  <ul>
    <li>HOME</li>
    <li>SERVICE</li>
    <li>ABOUT</li>
    <li>CONTACT</li>
  </ul>
</div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ishaan
  • 75
  • 9
  • As the question is currently closed as duplicate, in that duplicated question the answers are pretty old. To achieve what you want ( right text and inverse position of the elements ) you can remove `float:right` from `li` and add `display:flex; flex-direction:row-reverse` on the `ul`. Float gets the elements out of the normal flow of the document, so adding `float:right` on `li` makes the `ul` to consider that it doesn't have content , so `height:0;width:0` on the ul – Mihai T Jun 15 '18 at 12:56

1 Answers1

0

This is because, if a parent element contains only floated elements, you need to clear the float or the height of the parent would literally collapse to nothing. You can check this SO thread for more info: How do you keep parents of floated elements from collapsing?.

EDIT: Thanks to Andrew Bone for pointing this out, but your layout is possible to achieve without using floats as well.

body {
  margin: 0;
  padding: 0;
}

div {
  background-color: black;
  color: red;
  padding-top: 2px;
  padding-bottom: 2px;
}

li {
  display: inline;
}

ul {
  list-style-type: none;
  text-align: right;
}
<h1>BUSINESS NAME</h1>

<div>
  <ul>
    <li>HOME</li>
    <li>SERVICE</li>
    <li>ABOUT</li>
    <li>CONTACT</li>
  </ul>
</div>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Amit
  • 1,620
  • 1
  • 15
  • 24
  • 1
    Giving the div `text-align: right;` will have the same result without having to float anything – Andrew Bone Jun 15 '18 at 12:44
  • 1
    You are right.. I will update the answer – Amit Jun 15 '18 at 12:47
  • @AndrewBone @Amit `text-align :right` doesn't solve the problem, as float right also reverses the order of the li's. `flex-direction:row-reverse` would achieve this – Mihai T Jun 15 '18 at 12:53
  • Thank Andrew & Amit for quick response. I was aware of both of these solutions text-align & Overflow for creating my layout. But Was not aware of why this is happening with float Elements. Provided Thread helped me to understand.. – Ishaan Jun 15 '18 at 12:58