是否有任何方法可以只使用css来动态地对两个对象进行中心化?所谓动态中心,我的意思是,如果其中一个对象的大小发生变化,css就不会发生更改。
现在,要使用下面的css实现这一非动态im,是否有一种方法可以做到这一点,而无需事先知道子元素的高度大小,从而无法正确地设置top:和left:?
<div class="box">
<img src="myimageurl" width="100" height="100">
</div>CSS
.box {
width: 200px;
height: 200px;
background: red;
}
.box img {
margin-top: 50%;
margin-left: 50%;
position:relative;
/* These are the values id like to dynamically set */
top: -50px; /* being half of the image height */
left: -50px; /* being half of the image width */
}我在这里做了一个js小提琴: http://jsfiddle.net/gnygxbxe/
发布于 2015-05-15 23:44:40
你不需要计算任何百分比的位置。使用伪元素对其进行居中。您只需要确保内部的所有元素都具有属性display: inline-block和vertical-align: middle。
请记住,框内的元素应该在一行中。因此,如果您想要放置许多文本,只需将文本包装为span或.box元素中的任何内容即可。
有关参考资料,请阅读以下内容:https://css-tricks.com/centering-in-the-unknown/
看这个片段。支持IE8+。
.box {
margin: 20px;
background: #f8f8f8;
border: #f0f0f0 solid 1px;
text-align: center;
white-space: nowrap;
}
.box:before {
content: '';
display: inline-block;
height: 100%;
margin-right: -0.15em;
vertical-align: middle;
}
.box > * {
display: inline-block;
padding: 15px;
border: 1px solid #ccc;
vertical-align: middle;
}<div class="box" style="height: 300px;">
<img src="http://placehold.it/100x100" />
</div>
发布于 2015-05-15 11:52:27
垂直对中使用display: table-cell、vertical-align,水平对中使用text-align。
.img {
display: table-cell;
vertical-align: middle;
text-align: center;
}发布于 2015-05-15 11:54:43
.box {
width: 200px;
height: 200px;
background: red;
}
.box img {
position:relative; top: 50%; left: 50%;
-webkit-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}<div class="box">
<img src="http://www.reviversoft.com/blog/wp-content/uploads/2013/08/Spinning-Beach-Ball1.png" width="100" height="100">
</div>
https://stackoverflow.com/questions/30258808
复制相似问题