Html 如何垂直对齐两个浮动的 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10561162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I vertically align two floated divs?
提问by HymanMahoney
I have two divs inside a container div. One need to float left the other float right. They also both need to be vertically centered inside their parent. How can I achieve this?
我在容器 div 中有两个 div。一个需要向左浮动,另一个需要向右浮动。它们也都需要在其父级内部垂直居中。我怎样才能做到这一点?
<div id='parent'>
<div id='left-box' class='child'>Some text</div>
<div id='right-box' class='child'>Details</div>
</div>
If no float is applied to either they vertically align to the middle with this css
如果没有浮动应用于它们,它们将使用此 css 垂直对齐到中间
.child{ display:inline-block; vertical-align:middle; }
However adding #right-box{ float: right; }
causes the children to lose their vertical alignment. What am I doing wrong?
然而,添加#right-box{ float: right; }
会导致孩子失去垂直对齐。我究竟做错了什么?
Thanks guys
谢谢你们
回答by Vladimir Starkov
hereis the online demo of the solution you needed
这是您需要的解决方案的在线演示
it was made with this html:
它是用这个 html 制作的:
<div id='parent'>
<div id='left-box' class='child'>Some text</div>
<div id='right-box' class='child'>Details</div>
</div>
and this css:
和这个CSS:
#parent {
position: relative;
/* decoration */
width: 500px;
height: 200px;
background-color: #ddd;
}
.child {
position: absolute;
top: 50%;
height: 70px;
/* if text is one-line, line-height equal to height set text to the middle */
line-height: 70px;
/* margin-top is negative 1/2 of height */
margin-top: -35px;
/* decoration */
width: 200px;
text-align: center;
background-color: #dfd;
}?
#left-box { left: 0; }
#right-box { right: 0; }
回答by D.B.
You can try the display:table and display:table-cell styles.
Check this site out for more details http://www.quirksmode.org/css/display.html
您可以尝试 display:table 和 display:table-cell 样式。
查看此站点以获取更多详细信息http://www.quirksmode.org/css/display.html
NB: if you want the parent div height to be a percent (like 100%), then it will be relative to the height of it's container. If the container is the body, then you will have to set the body and html's height as well, like to 100%.
注意:如果您希望父 div 高度为百分比(如 100%),那么它将相对于其容器的高度。如果容器是主体,那么您还必须设置主体和 html 的高度,例如 100%。
Here's an example of what the code might look like:
下面是代码可能是什么样子的示例:
<div id='parent'>
<div id='left-box'>Some text</div>
<div id='right-box'>Details</div>
</div>?
<style>
body,html{
height:100%;
}
#parent{
border:1px solid red;
display:table;
height:100%;
width:100%;
}
#left-box{
background-color:#eee;
display: table-cell;
vertical-align:middle;
padding:3px;
width:50%;
}
#right-box{
background-color:#dddddd;
display: table-cell;
vertical-align:middle;
padding:3px;
width:50%;
}
?</style>