Reputation: 8101
All of the widths and margins come out to a total of 99.96%, so it should fit just fine in the 100%. I understand that borders add width, so I've done box-sizing: border-box;
but that doesn't seem to fix it. If I float: left
then it works okay in Chrome, but I feel like that's a crappy workaround anyway and doesn't actually fix the problem.
Why doesn't it all fit on one line?
HTML
<div id="container">
<a href="#">
1
</a>
<a href="#">
2
</a>
<a href="#">
3
</a>
<a href="#">
4
</a>
</div>
CSS
body {
border: 1px solid black;
background-color: #BCCDDC;
margin: 5% 25%
}
#container a {
font-family: 'Open Sans', sans-serif;
text-align: center;
box-sizing: border-box;
-webkit-box-sizing: border-box;
border: 2px solid #fff;
display: inline-block;
width: 15%;
margin: 0 6.66%;
padding: 20px 0;
}
#container a:first-of-type {
margin-left: 0 !important;;
}
#container a:last-of-type {
margin-right: 0 !important;
}
Upvotes: 3
Views: 421
Reputation: 4033
As mentioned in other answers the whitespace between your elements is the issue here.
Though you can use float: left
here, you just have to keep two things in mind:
overflow: auto
to fix that#container {
overflow: auto;
}
#container a {
float: left;
}
#container a:last-child {
float: right;
}
Upvotes: 1
Reputation: 2854
If you don't want to deal with manually setting the margins, you could use display: flex
and justify-content: space-between
.
Just add the two styles to the parent, and remove the margin from the child
#container {
display: flex;
justify-content: space-between;
}
Upvotes: 1
Reputation: 92903
inline-block
elements aren't floated; they're inline, which means white space between elements is preserved.
You can fix this by removing the whitespace entirely between <a>
tags: http://jsfiddle.net/mblase75/y1Ltq1fc/4/
<a href="#">
1
</a><a href="#">
2
</a><a href="#">
3
</a><a href="#">
4
</a>
Alternatively, make the anchors float: left
and put overflow: auto
on the parent #container
: http://jsfiddle.net/mblase75/y1Ltq1fc/9/
#container {
overflow: auto;
}
#container a {
float: left; /* automatically sets display:block */
/* etc. */
}
Here are some other techniques, if you have a problem implementing the above.
Upvotes: 7
Reputation: 14173
display: inline-block;
honors whitespace between elements, to fix it you can either:
Remove the whitespace between the elements in the HTML
<div id="container">
<a href="#">1</a><a href="#">2</a><a href="#">3</a><a href="#">4</a>
</div>
Make the font-size zero on the container in CSS
#container {
font-size: 0;
}
#container a {
font-size: 12px;
}
Upvotes: 3