Reputation: 58434
I'm trying to create a menu list item which has 4 items but it doesn't feed inside one line for some reason. I tried nested it with nested divs but had no luck. The problem starts to happen when I added the padding: 10px;
.
Here is the latest HTML and CSS I have:
HTML:
<div id="header">
<ul id="menu">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Info</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
CSS:
#menu {
margin: 0;
padding: 0;
}
#menu li {
display: block;
float: left;
margin: 0;
width: 25%;
background-color: gray;
padding: 10px;
}
I also have a jsfiddle for that: http://jsfiddle.net/GLh92/1/
As you can see, it doesn't fit inside the one line. I also have a responsiveness concern here. So, it needs to fit inside one line for different screen resolutions.
Any idea how this can be done in a clean way?
Upvotes: 3
Views: 16446
Reputation: 394
Padding adds width and/or height to your elements, you should handle padding or margin with the children of your li elements.
Upvotes: 0
Reputation: 782
The problem is that you are setting the width to 25% to each of the li element. You have four list elements, its fine as long as there is no padding ( 25*4 = 100 ) But when you add padding one of the element moves to to next line.( 25*4 + 10(padding) > 100 )
change the value of width to something else line 15%
#menu li {
display: inline-block;
float: left;
margin: 0;
width: 15%;
background-color: gray;
padding: 10px;
}
Upvotes: 0
Reputation: 10772
The solution is to add the padding to the <a>
tags, instead of the <li>
tags since padding adds to the actual width.
<li>
padding: 10px;
to <a>
<a>
tagsHTML:
<div id="header">
<ul id="menu">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Info</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
CSS:
#menu {
margin: 0;
padding: 0;
}
#menu li {
display: block;
float: left;
margin: 0;
width: 25%;
background-color: gray;
}
#menu li a {
display: block;
padding: 10px;
}
Upvotes: 1
Reputation: 520
When you mention padding:10px;
its also increases the width of the <li>
item. So you need to take care of width:20%;
Try this:
#menu li {
display: block;
float: left;
margin: 0;
width: 20%;
background-color: gray;
padding:10px;
}
It will comes under the same line. Is this what are you looking for ?
Upvotes: 0
Reputation: 191729
Use box-sizing: border-box
on the li
elements. This will make the padding part of the width calculation.
http://jsfiddle.net/ExplosionPIlls/GLh92/5/
Upvotes: 5
Reputation: 7180
Look into the box-sizing css property, it will change your life.
#menu li {
display: inline-block;
float: left;
margin: 0;
width: 25%;
background-color: gray;
padding: 10px;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
Upvotes: 4