-2

I have the following HTML code with some internal CSS:

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333333;
}
li {
  float: left;
}
li a {
  display: block;
  color: white;
  text-align: center;
  padding: 16px;
  text-decoration: none;
}
li a:hover {
  background-color: #111111;
}
<ul>
  <li><a class="active" 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>

The above code displays a horizontal menu.

As per my knowledge, unless we use display: inline property we can't display a list horizontally. Then how could it happen in above code where display: inline property has not been used and still the list is displayed horizontally?

Someone please explain me.

Thanks.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
PHPLover
  • 1
  • 51
  • 158
  • 311
  • 2
    Who told you «unless we use "display:inline" property we can't display a list horizontally» ? That's false, and your example proves it. – Oriol Aug 28 '16 at 20:59

2 Answers2

3

As per my knowledge, unless we use display: inline property, we can't display a list horizontally. Then how could it happen in above code where display: inline property has not been used and still the list is displayed horizontally?

Actually, there are several ways to display elements on the same row. Here are just a few:

  • display: inline
  • display: inline-block
  • display: flex (on the parent)
  • create a custom element with no display specified

and, like in your code:

  • float: left

From MDN:

The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it.

Also, the initial value of the display property is inline.

This means that all elements are display: inline, by default. (Hence, why custom elements appear on the list above.)

It isn't until a browser parses its default style sheet that some elements become display: block and render on separate lines.

Here's a more in-depth explanation: Proper way to apply CSS to HTML5 custom elements

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
0

Remove float: left from the css, becaue it also inline the list. see below

li {
  float: left;
}
Yasir Khan
  • 512
  • 3
  • 18