[英]Why cant center an image inside a 'div' with 'float' right or left?
我在嵌套的div .box
包含了一个图像。 如果它没有浮动,则图像可以精确地居中于.box
,但是当我left
或right
float
时,中心对齐就会消失! 我有4张各种尺寸的图片需要在他们自己的.box
中心。 我该如何解决?
HTML
<div class="con">
<div class="box">
<img src="../_images/icon-test.png">
</div>
</div>
CSS
.con {
width:300px;
height:200px;
background: #996600;
}
.box {
position:relative;
width:150px;
height:150px;
background-color: #333333;
display:table-cell;
text-align:center;
vertical-align:middle;
float:right;
}
您可以使用display: flex
来实现此目的。
更改display: table-cell
to display: flex
。
然后改变text-align:center;
和vertical-align:middle;
align-items: center;
并justify-content: center;
使其垂直和水平居中。
编辑:然后我还为图像添加了150px的最大宽度,以便在图像大于它时阻止它从容器中扩展出来。 向@Hkidd道具指出这种情况发生了。
.con { width: 300px; height: 200px; background: #996600; } .box { position: relative; width: 150px; height: 150px; background-color: #333333; display: flex; align-items: center; justify-content: center; float: right; } img { max-width: 150px; }
<div class="con"> <div class="box"> <img src="http://placehold.it/200x100"> </div> </div>
说明
我认为你必须定位img
absolute
,所以它将被定位绝对其父.box
,因为.box
相对位置。 还有display: table-cell;
因为img
不在表格内,所以是不必要的。
这就是我想出的:
.con { background: #996600; height: 200px; width: 300px; } .box { background-color: #333333; float: right; height: 150px; position: relative; width: 150px; } .box img { bottom: 0; left: 0; margin: auto; position: absolute; right: 0; top: 0; width: 90%; }
<div class="con"> <div class="box center"> <img src="http://placehold.it/120x100"> </div> </div>
如果问题中有单个图像,则可以使用line-height
解决方案将图像精确放置在.box
div的中心,并在图像上使用vertical-align: middle
。 适用于所有浏览器并且易于理解。
参考代码:
.con { width: 300px; height: 200px; background: #996600; } .box { position: relative; width: 150px; height: 150px; background-color: #333333; text-align: center; vertical-align: middle; float: right; line-height: 150px; } img { height: 60px; vertical-align: middle; }
<div class="con"> <div class="box"> <img src="http://www.w3schools.com/css/img_fjords.jpg"> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.