Definitely not! That’s the most common way to do it.
If I don’t use float at all, there is a gap between list items
I still think that your first variant, using only inline-block and no float, is the best one.
The spaces between the elements are caused by the spaces (indents) in your HTML code between the li elements. You can either remove them by putting all of the li elements on one line in your code, or by putting the space between them in a comment, as I prefer to do and have demonstrated below:
body {
margin: 0px;
padding: 0px;
}
div {
text-align: center;
background-color: gray;
margin: 0px;
padding: 0px;
}
ul {
list-style-type: none;
margin: 0px;
padding: 0px;
display: inline-block;
}
ul li {
display: inline-block;
color: white;
background-color: blue;
}
I was trying to create a horizontal navbar using lists inside a container div, I came across confusing things.
When I try to place elements next to each other, if I dont use float at all, there is a gap between list items, but margin and padding wise it is fine.
body {
margin: 0px;
padding: 0px;
}
div {
text-align: center;
background-color: gray;
margin: 0px;
padding: 0px;
}
ul {
list-style-type: none;
margin: 0px;
padding: 0px;
display: inline-block;
}
ul li {
display: inline-block;
color: white;
background-color: blue;
}
To solve that, I used font-size: 0px and font-size: 16px for <ul>.
That solved my problem but I don’t know if it’s right thing to do and more importantly what causes the problem there.
body {
margin: 0px;
padding: 0px;
}
div {
font-size: 0px;
text-align: center;
background-color: gray;
margin: 0px;
padding: 0px;
}
ul {
font-size: 16px;
list-style-type: none;
margin: 0px;
padding: 0px;
display: inline-block;
}
ul li {
display: inline-block;
float: left;
color: white;
background-color: blue;
}
Is it bad to use list items as navigation bars or I am using it wrong? I am curious what causes that gap at the bottom of the list.
Comments
Comment posted by Temani Afif
in the second case don’t use font-size, adjust the vertical-align like suggested/explained in the duplicate. For the first snippet it’s the comming case of space between inline-block (check the second duplicate)
Comment posted by alexmoran
@TemaniAfif Thanks so much but there is one thing I didn’t fully understand. When not using float, we didn’t have to vertical align list, but in the other case where list items were floated, there is a gap which can be fixed by vertical align. Why is there a difference?
Comment posted by Temani Afif
the default vertical-align is the baseline. With float the basline is the bottom of your element so we need space under it (like the image in the duplicate). Without float the baseline is different and is based on the text inside. Add
Comment posted by stackoverflow.com/q/9273016/8620333
check this:
Comment posted by alexmoran
@TemaniAfif Sorry if it’s too silly but why did floating change baseline? I mean isn’t there some list items in both situations?