Why should an ol element's overflow attribute be hidden, to expand it as much as possible in the x-axis direction

45 Views Asked by At

I made a simple navigation menu that detects hover over buttons and changes color. I refered to this.

index.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>

<ul class="menu_button_container">
  <li><a href="about:blank" class="menu_button">hi</a></li>
  <li><a href="about:blank" class="menu_button">bye</a></li>
  <li><a href="about:blank" class="menu_button">asfd</a></li>
</ul>

</body>
</html>

style.css

li {
    float: left;
  }
  
  .menu_button{
    padding: 10px 12px;
    display: inline-block;
    text-align: center;
    color: white;
    text-decoration: none;
  }
  .menu_button:hover {
    background-color: #111;
  }

  .menu_button, .menu_button_container{
    background-color: gray;
  }
  .menu_button_container{
    list-style-type: none;
    margin: 0px;
    overflow: hidden;  <!--here the problem line-->
    padding: 0px;
    width:100%;
  }

If I delete the problem line, ol element doesn't expand in x-axis direction.

I try to delete the problem line, expecting the program will operate without change.

It is completely different from my expectation. According to what I leared, overflow property determines how to react when the element 'overflows' but the width of the ol element is too short to overflow.(its parent is body)

1

There are 1 best solutions below

3
Jacob On

float: left; takes your <li> out of the normal flow of the document. This means they don't contribute to the height of their parent element. The overflow property, when set to a value other than visible, establishes a new block formatting context. This means the parent element contains the floated elements, causing it to expand to include them. If you remove overflow: hidden; the menu_button_container doesn't establish a new block formatting context, and won't expand to include the floated elements. To solve this you need to clear the floats:

.menu_button_container::after {
    content: "";
    display: table;
    clear: both;
}