[英]How to vertically align div inside another div without display:table-cell
好的,这是div结构。
<div class="DivParent">
<a href="#">
<div class="DivWhichNeedToBeVerticallyAligned"></div>
</a>
</div>
DivParent具有固定的宽度和高度值,但DivWhichNeedToBeVerticallyAligned没有固定的高度值。
如果你做DivParent显示:table-cell; 你可以垂直对齐DivWhichNeedToBeVerticallyAligned,但我不想使用该功能,因为它会导致一些混乱。
一个href标签链接应该与divParent的大小相同我的意思是整个divparent必须是可点击的。 喜欢显示:块。
那么有任何CSS方式的垂直对齐或轻量级jquery解决方案也会有所帮助。
谢谢。
在这里jsfiddle : http : //jsfiddle.net/XHK2Z/
*
您可以使用一个额外的帮助来获得与固定高度块垂直对齐。
看看这个: http : //jsfiddle.net/kizu/7Fewx/
在那里,您必须在要对齐的块附近有一个帮助器:
.DivHelper {
display: inline-block;
vertical-align: middle;
height:100%;
}
并添加display: inline-block; vertical-align: middle;
display: inline-block; vertical-align: middle;
到.DivWhichNeedToBeVerticallyAligned
如果不知道子div的高度,就无法用CSS做到这一点。
使用jQuery,你可以做这样的事情。
var parentHeight = $('#parent').height();
var childHeight = $('#child').height();
$('#child').css('margin-top', (parentHeight - childHeight) / 2);
这个解决方案适用于包括IE 10及更高版本在内的现代浏览器。
<div class="parent">
<div class="child">Content here</div>
</div>
包括这个css
.parent {
height: 700px;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width : 525px;
}
如果父母没有任何其他孩子。 这将是一个只有“黑客”的CSS
DivParent{line-height:100px /*the div actual height*/ }
.DivWhichNeedToBeVerticallyAligned{display:inline-block}
另一个黑客是
DivParent{height:100px; position:relative}
.DivWhichNeedToBeVerticallyAligned{height:20px; position:absolute; top:50%; margin-top:-10px;}
我一直在使用以下解决方案(没有定位,没有table-cell / table-row和没有行高),因为一年多来,它也适用于IE 7和8。
<style>
.outer {
font-size: 0;
width: 400px;
height: 400px;
background: orange;
text-align: center;
display: inline-block;
}
.outer .emptyDiv {
height: 100%;
background: orange;
visibility: collapse;
}
.outer .inner {
padding: 10px;
background: red;
font: bold 12px Arial;
}
.verticalCenter {
display: inline-block;
*display: inline;
zoom: 1;
vertical-align: middle;
}
</style>
<div class="outer">
<div class="emptyDiv verticalCenter"></div>
<div class="inner verticalCenter">
<p>Line 1</p>
<p>Line 2</p>
</div>
</div>
这是现代浏览器的另一种选择:
.child {
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.