有没有办法仅使用 css 动态居中两个对象?动态居中是指如果其中一个对象的大小发生变化,CSS 不会发生变化。
目前要使用下面的CSS实现这种非动态im,有没有办法在事先不知道子元素的高度尺寸的情况下做到这一点,从而无法设置top:
和 left:
正确吗?
HTML
<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/
最佳答案
您不需要计算任何百分比位置。使用伪元素将其居中。您只需确保其中的所有元素都具有属性 display: inline-block
和 vertical-align: middle
。
请记住,框内的元素应位于 1 行中。因此,如果您想放置大量文本,只需将文本包装为 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>
关于html - 使用 css 动态居中对齐元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30258808/