danwoods
danwoods

Reputation: 4907

Basic CSS positioning (fitting children in container)

Very basic CSS question. Given the code shown in http://jsfiddle.net/danwoods/65X7X/ why don't the child divs (the colored blocks) fit into the container element?

CSS from fiddle

.container {
    width: 360px;
    height: 50px;
    border: 1px solid black;
}
.container div {
    width: 120px;
    height: 100%;
    display: inline-block;
}
.one {
    background: blue;
}
.two {
    background: green;
}
.three {
    background: red;
}

Thanks in advance,
Dan

Upvotes: 1

Views: 390

Answers (4)

j08691
j08691

Reputation: 207861

Because inline elements are sensitive to white space. You can remove them so the HTML looks like:

<div class="container">
    <div class="one"></div><div class="two"></div><div class="three"></div>
</div>

jsFiddle example

Or float the divs left:

.one,.two,.three {
    float:left;
}

jsFiddle example

Or use HTML comments to eat up the white space:

<div class="container">
    <div class="one"></div><!--
    --><div class="two"></div><!--
    --><div class="three"></div>
</div>

jsFiddle example

Upvotes: 4

Hiigaran
Hiigaran

Reputation: 831

While putting literally no spaces between the divs in your code, or using HTML comments both work equally well, there is a better solution. In my opinion, the most elegant solution, by which I mean the way which does not involve having to mess up the look and readability of your code, is to add this line of CSS:

body>.container{font-size:0;}

If your body tag is not the parent of .container, replace body with whatever the parent is. This line basically says that the styles will apply to the .container class, but only that specific class. Not the child elements of .container. So by applying a font size of 0, you eliminate the gaps made by it, thereby bringing everything into alignment.

http://jsfiddle.net/65X7X/6/

Upvotes: 1

Manish Pradhan
Manish Pradhan

Reputation: 1188

Its not a bug. You can see here why it happens and how you can overcome the problem.

http://css-tricks.com/fighting-the-space-between-inline-block-elements/

Upvotes: 1

taxicala
taxicala

Reputation: 21759

You have to float them left:

http://jsfiddle.net/65X7X/2/

.container div {
    width: 120px;
    height: 100%;
    display: inline-block;
    float: left;
}

Hope this helps.

Upvotes: 1

Related Questions