Sebastian
Sebastian

Reputation: 3628

Nested div vertical align problem

I am trying to vertically center one div (containing a search bar) inside another (a top banner). I was under the impression that to do so you did the following:

#banner {
height: 35px;
width: 100%;
}

#searchbar {
    height: 15px;
    position: relative;
    top: 50%;
    margin-top: -7.5px; /* half of the height */
}

This works fine until you add the margin-top at which point it is applied to the #banner as well.

Is there an alternative way to do this, or am I just doing it wrong?

Here's a jsFiddle of my actual code.

Upvotes: 0

Views: 2088

Answers (3)

ngen
ngen

Reputation: 8966

I use line-height with the value being the same as height of parent div.

As seen here: http://jsfiddle.net/vkJ78/24/

CSS:

#banner    {
    background-color: #770E17;
    height: 35px;
    width: 100%;
    border-bottom: 1px solid #333;
    }

#src    {
    width: 300px;
    height: 15px;
    border: 1px solid #333;
    padding: 3px;
    }

#srcdiv {
    width: 308px;
    margin: 0px auto;
    position: relative;
    line-height: 35px;
}

EDIT: Per recommendation from NGLN, this will also fix horizontal centering, #srcdiv and #src having equal widths.

Upvotes: 4

Mr.T.K
Mr.T.K

Reputation: 2356

Give margin:0px and padding:0px and remove margin-top

body {
    margin:0px;
    padding:0px;

}

Upvotes: 0

Rauzippy
Rauzippy

Reputation: 61

You have to add overflow: hidden to #banner. To clear the float, I guess.

Then, modify the negative margin to margin-top: -11px in #srcdiv (you have to sum the div height, the border, and the padding for the total height)

http://jsfiddle.net/vkJ78/1/

Upvotes: 1

Related Questions