Reputation: 3628
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
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
Reputation: 2356
Give margin:0px
and padding:0px
and remove margin-top
body {
margin:0px;
padding:0px;
}
Upvotes: 0
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)
Upvotes: 1