问题
Well, I got this structure:
#parent{
max-width: 800px;
height: auto;
margin: auto;
}
#child{
position: absolute;
width: 100%;
height: 52px;
display: none;
}
<div id="parent">
<div id="child"></div>
</div>
The child div is hidden per default. It gets visible by using jQuery (.fadeIn). Now the question is, how can I vertically center the child element by using only css?
回答1:
I have created a prototype... But I had to modify your HTML and CSS so it might not be the best solution: http://jsfiddle.net/TmCwB/
HTML
<div id="outerDiv">
<div id="parent">
<div id="child"></div>
</div>
</div>
CSS
#outerDiv {
margin: 0 auto;
width: 200px;
}
#parent{
background-color: red;
display: table-cell;
vertical-align: middle;
text-align: center;
width: 200px;
height: 500px;
}
#child{
width: 100%;
height: 52px;
display: inline-block;
background-color: blue;
}
Hope this helps...
回答2:
#child{
position: absolute;
width: 100%;
height: 52px;
/*display:none;*/
display: block;
background-color: blue;
top:50%;
}
just add top:50% to your CSS code.
http://jsfiddle.net/nirus/dry2Q/
回答3:
Ok guys. Thank you for your answers. Atrox11's answer was the right one but I found out that there was another issue that I had to deal with.
There's another wraper div. Since all my children divs are positioned absolute, the parent div had a height of 0px. This was the actual fault. After I fixed that, everything worked as expected.
Sorry for the question. I would appreciate it, if you won't rate it down, since everyone makes some mistakes when he is in a hurry.
来源:https://stackoverflow.com/questions/17326981/vertically-center-div-in-a-div-with-height-auto