Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does adding text do a div change the margin [duplicate]

Tags:

html

css

I don't understand why adding a text do a div seems to be changing how the div is parsed by the browser? Looks like the margin-top is changed, though it isn't.

HTML

<div id="nav">
  <div class="nav-left">left</div>
  <div class="nav-logo"></div>
  <div class="nav-right">right</div>
</div>

CSS

#nav {
    width: 400px;
    height: 30px;
    background: #f5f5f5;
    border: 1px solid grey;
    text-align: center;
}
.nav-left, .nav-right, .nav-logo {
    display: inline-block;
    height: 30px;
}
.nav-left {
    background: red;
}
.nav-right {
    background: blue;
}
.nav-right, .nav-left {
    width: 50px;
}
.nav-logo {
    background: yellow;
    width: 30px;
    margin-left: 10px;
    margin-right: 10px;
}

Code is also here: http://jsfiddle.net/NcA8r/

like image 241
Andreas Avatar asked Oct 01 '22 21:10

Andreas


2 Answers

As @JoshCrozier said, you need to add a vertical-align to your 3 divs.

This:

.nav-left, .nav-right, .nav-logo {
    display: inline-block;
    height: 30px;
}

Should be:

.nav-left, .nav-right, .nav-logo {
    display: inline-block;
    height: 30px;
    vertical-align:top;
like image 159
ᔕᖺᘎᕊ Avatar answered Oct 03 '22 11:10

ᔕᖺᘎᕊ


It happens because you used display: inline-block; in your inner divs.

inline-block elements are vertical-align:baseline; by default.

Check this out this great answer.

"The default value for vertical-align in CSS is baseline."

And this one too.

like image 45
Itay Gal Avatar answered Oct 03 '22 11:10

Itay Gal