Why do Floating tag cause
  • to Float in CSS?
  • As we know one way to making horizontal menu is to floating list items left. but in most cases I saw, they making horizontal menu with CSS by using float property inside of <a> tags that are inside <li> tag. but why do float property of <a> tag cause its parent tag <li> floated to left? what’s the difference between using float property inside <li> and <a> tag? why don’t we use float:left inside <li> to make horizontal menu?

    ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      overflow: hidden;
      background-color: #333;
    }
    
    li a {
      display: inline-block;
      color: white;
      text-align: center;
      padding: 14px 16px;
      text-decoration: none;
      float: left;
    }
    
    li a:hover {
      background-color: #111;
    }
    <ul>
      <li><a href="#home">Home</a></li>
      <li><a href="#news">News</a></li>
      <li><a href="#contact">Contact</a></li>
      <li><a href="#about">About</a></li>
    </ul>

    Answer

    but why do float property of <a> tag cause its parent tag <li> floated to left?

    It doesn’t.

    Floating the a element takes it out of normal flow.

    The li element therefore has no content in normal flow.

    The default height, which hasn’t been overridden, of the li element is auto which gets computed as 0.

    This allows the following content to move up beside it.


    why don’t we use float:left inside <li> to make horizontal menu?

    Today we generally don’t, but when we did then floating the list item was the usual approach taken.

    float is designed to let content flow around images (etc) to create effects like this example from the CSS specification:

    example of floats

    Decades ago CSS lacked real layout tools and float was used as a hack.

    Today we have Flexbox and Grid which are designed for this type of layout.

    Leave a Reply

    Your email address will not be published. Required fields are marked *