Inline-block elements don't show as expected
I'm writing a style sheet, and I want to display three elements horizontally (width=33%) within a container, with a relative layout. Here's the code:
#container
{
margin:auto;
width:85%;
padding:0;
}
#element
{
display:inline-block;
width:33.3%;
margin-left:0;
margin-right:0;
border:0px;
text-align:center;
}
I don't understand why with three elements:
<div id="container">
<div id="element">hi</div>
<div id="element">every</div>
<div id="element">one</div>
</div>
The last element is shown below the first two, while I believed tha开发者_JAVA技巧t they would be drawn on the same line. There are no margins,padding or borders. If width is set to 32%, in a Full browser window, they are on the same line (it works), but when I reduce the browser-window width, the last element falls on a new line. Does anybody know why this happens?
These are inline blocks, so they get laid out just like characters would (think of them as really big characters, basically). And in your case you have whitespace between them, so that whitespace becomes a single space on the line between the inline-blocks in the rendering; you can see this if you put borders on them. So the space taken up by all three together ends up being "99.9% of container width plus width of two spaces in the container's font". When you reduce to 32%, then you get line-breaking once two spaces add up to more than 4% of the container width (which is why it only happens at smaller container widths).
If you really want your inline-blocks flush up against each other, take out the spaces between them.
Make you element a class (thanx Jarrett) and add float:left
style to that class.
.element
{
display:inline-block;
width:33.3%;
margin-left:0;
margin-right:0;
float:left;
border:0px;
text-align:center;
}
<div id="container">
<div class="element">hi</div>
<div class="element">every</div>
<div class="element">one</div>
</div>
I recommend to play arround with the containers width. A tip that works for me is giving them a line. Below is my contribution:
http://jsfiddle.net/8dWhF/
精彩评论