user3029001
user3029001

Reputation: 439

Positioning of child elements within parent

I'm trying to understand the basics of CSS and I ran into a problem where I have a nav element with 3 div elements inside of it. The div elements are displayed as inline-block so all elements are aligned in the nav element.

The problem occurs when I add a paragraph element inside the first div. Suddenly, the first div is not aligned to the other two. I used Chrome's developer tools to look at what happened. The div with the p element doesn't have any margins or paddings. The paragraph tag has, by default, 16px margin, but when I set it to 0, the container div still isn't aligned, so I don't think that's the problem.

Could someone explain what is causing the first div to move from its original position when I add a child element like p?

The height of p is smaller than the height of the containing div. The margin of p doesn't seem to matter because I set it to 0 and the div still isn't aligned.

JsFiddle: http://jsfiddle.net/jjF7R/

HTML

<nav>
 <div>
   <p>hi</p>
 </div>

 <div>
 </div>

 <div>
 </div>
</nav>

CSS

nav{
width:330px;
height:50px;
border:1px solid black;
display:inline-block;
}

div{
width:100px;
border:1px solid blue;
height:100%;
display:inline-block;
} 

Upvotes: 0

Views: 64

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206092

div{
    width:100px;
    border:1px solid blue;
    height:100%;
    display:inline-block;
        vertical-align: top; /* middle, bottom... whatever is needed */
}

https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align

It happens cause inline-block elements become subject to context flow entering in a world where line-heights rule, designers use Helvetica and mighty beasts are looking after your paddings ... :)

Upvotes: 1

Satwik Nadkarny
Satwik Nadkarny

Reputation: 5135

User

vertical-align:top;

for the div class in CSS.

Check this here -> http://jsfiddle.net/kA8sx/

Hope this helps!!!

Upvotes: 1

j08691
j08691

Reputation: 207901

You need to add vertical-align:top to the div rules:

div {
    width:100px;
    border:1px solid blue;
    height:100%;
    display:inline-block;
    vertical-align:top;
}

jsFiddle example

The default vertical alignment for inline elements is baseline, which is what you see in your original code.

Upvotes: 2

Related Questions