图像居中与背景图像:网址与图像标记

问题描述 投票:0回答:1

我有一种情况,我想使用背景图像而不是图像标签。屏幕大小的图像大小调整在这里很重要...第一个例子是我想要的...图像调整大小但在高度降低到300px时停止。然后,如果屏幕尺寸变得非常窄,则图像保持居中,并且两个尺寸的末端都会被裁剪。这可以通过object-fit:cover轻松实现

第二个div使用背景图像并且几乎可以工作,但是当屏幕变窄时,我无法使图像居中。注意图像刚刚被裁剪成正确的尺寸。

.myimgtag {
width:100%;
height:auto;
min-height:300px;
object-fit:cover}



.mybackgroundimg {
background-image:url('https://www.panotools.org/dersch/StBp.JPG');
background-size:cover;
background-repeat:no-repeat;
min-height:300px;  
max-height: 2000px;
max-width: 2000px;
}
.mybackgroundimg:before {
content: "";
display: block;
padding-bottom: 50%;
}
<div>
<img class='myimgtag' src='https://www.panotools.org/dersch/StBp.JPG'>
</div>

<br><br>

<div class='mybackgroundimg'></div>
html css background-image centering
1个回答
1
投票

在第二张图片上,你试过background-position吗?

.myimgtag {
width:100%;
height:auto;
min-height:300px;
object-fit:cover}



.mybackgroundimg {
background-image:url('https://www.panotools.org/dersch/StBp.JPG');
background-position: center;
background-size:cover;
background-repeat:no-repeat;
min-height:300px;  
max-height: 2000px;
max-width: 2000px;
}
.mybackgroundimg:before {
content: "";
display: block;
padding-bottom: 50%;
}
<div>
<img class='myimgtag' src='https://www.panotools.org/dersch/StBp.JPG'>
</div>

<br><br>

<div class='mybackgroundimg'></div>
© www.soinside.com 2019 - 2024. All rights reserved.