CSS 在 div 中居中任何图像
CSS center any image in div
假设我有 div
,width: 300px
和 height: 200px
我希望这个 div
中的任何图像无论图像大于还是小于 div
;
水平和垂直居中
对于较小的图像 margin: 0 auto
效果很好,但较高的图像向右突出并且没有居中。
对于更大的图像,此方法有效:
height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
我找不到这些的任何组合,也没有找到任何解决方案来完美居中此图像。
试试这个
div{
display: flex;
align-items: center;
justify-content: center
}
将 position: absolute
添加到 img
并将 position: relative
添加到 div
.el {
position: relative;
width: 100px;
height: 100px;
border: 1px solid black;
margin: 50px 150px;
}
img {
opacity: 0.4;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: absolute;
}
<div class="el">
<img src="http://placehold.it/350x150">
<img src="http://placehold.it/50x50/000000/ffffff">
</div>
假设我有 div
,width: 300px
和 height: 200px
我希望这个 div
中的任何图像无论图像大于还是小于 div
;
对于较小的图像 margin: 0 auto
效果很好,但较高的图像向右突出并且没有居中。
对于更大的图像,此方法有效:
height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
我找不到这些的任何组合,也没有找到任何解决方案来完美居中此图像。
试试这个
div{
display: flex;
align-items: center;
justify-content: center
}
将 position: absolute
添加到 img
并将 position: relative
添加到 div
.el {
position: relative;
width: 100px;
height: 100px;
border: 1px solid black;
margin: 50px 150px;
}
img {
opacity: 0.4;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
position: absolute;
}
<div class="el">
<img src="http://placehold.it/350x150">
<img src="http://placehold.it/50x50/000000/ffffff">
</div>