Centering vertically relative to another element in css?
I've got something like the following situation:
<div id="container">
<div id="prev">
prev
</div>
<div id="content">
some content
</div>
<div id="next">
next
</div>
</div>
Where what I'd like is for the 开发者_开发知识库result to look something like this:
Note that prev and next are centered vertically in reference to Content and that all of it is centered horizontally on the page.
Sorry if this has been covered before but there seems to be a lot of different ways to do similar things and I'm unsure of which apply to this situation. CSS3/HTML5 isn't really a problem as long as it works in Chrome, Safari, Firefox and maybe IE (not crucial).
EDIT: Also, I'm not sure if this is really clear in the question, but I don't know the size of Content. It could be anything.
EDIT 2: Additionally, content is usually an image.
There's a couple of ways of doing this, my choice is using display: table-cell on the container and vertical-align: middle. the catch is that you can't put position absolute on the container:
#container {
border: solid #000 1px;
display: table-cell;
vertical-align: middle;
height: 400px;
width: 400px;
text-align: center;
}
#container div {
display: inline-block;
}
#content {
border: solid #000 1px;
padding: 10px;
width: 200px;
}
Works on IE8+ and modern browsers.
http://jsfiddle.net/E97yY/
Another approach, this time using absolute positioning, if you're willing to change your HTML structure a bit. Note that the Prev and Next buttons could be anywhere within the content div, even outside of the content div if you wanted to use your container to constrain the width, or perhaps add another width-constraining wrap. (Not really necessary, I'd imagine.)
Note: I've removed all unnecessary markup from this answer. See the fiddle for a visibly functioning example.
Fiddle
The HTML:
<div id="container">
<div id="content">
<div id="prev">prev</div>
<div id="next">next</div>
some content
</div>
</div>
The CSS:
#content {
margin:0 auto;
position:relative;
}
#prev, #next {
position:absolute;
width:40px;
height:20px;
top:50%;
margin-top:-10px; /* negative half of height */
}
#prev {
left:-45px; /* negative [width plus any desired padding] */
text-align:right;
}
#next {
right:-45px; /* negative [width plus any desired padding] */
text-align:left;
}
The best way to center elements is to use inline-blocks
and vertical-align
.
Here is a fiddle for a start: http://jsfiddle.net/kizu/7Qj3G/
Here you set display: inline-block
to needed elements, add vertical-align: middle
to them and it's almost done.
The remaining thing is that if you need support in IE, then you'll need to “turn on” the inline-block
behavior for block-level elements by using display: inline; zoom: 1;
on them.
精彩评论