Archimedis
Archimedis

Reputation: 233

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 that 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?

Upvotes: 1

Views: 550

Answers (3)

gutierrezalex
gutierrezalex

Reputation: 828

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/

Upvotes: 0

Boris Zbarsky
Boris Zbarsky

Reputation: 35064

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.

Upvotes: 4

MeLight
MeLight

Reputation: 5565

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>

Upvotes: 0

Related Questions