我正在尝试调整背景图片的大小以适应div。我的问题是,我希望图像适应div的高度并保持比例。例如,我有一个div,不希望它超出屏幕的宽度(以防止出现滚动条),我想使用的图像为1024px X 400px。如果我尝试适应图像的高度,它将强制适应宽度,从而失去比例。我不在乎图像的某些部分是否被显示。实际上,这就是我想要做的。
需要使用哪些标签?HTML5还是CSS?
需要使用哪些标签?HTML5还是CSS?
background-size: cover;
来填充<div>
,或者使用background-size: auto 100%;
如果您只想匹配高度而不关心侧面的过度或欠流:
html,
body {
position: relative;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
div {
background-image: url(https://placebear.com/1024/400.jpg);
display: inline-block;
background-repeat: no-repeat;
border: 1px solid black;
}
.cover {
background-size: cover;
}
.center {
background-position: center;
}
.height {
background-size: auto 100%;
}
<h1>Unstyled</h1>
<div style="width: 50px; height: 200px"></div>
<div style="width: 200px; height: 50px"></div>
<div style="width: 125px; height: 125px"></div>
<h1>Un-centered</h1>
<h2>Cover</h2>
<div class="cover" style="width: 50px; height: 200px"></div>
<div class="cover" style="width: 200px; height: 50px"></div>
<div class="cover" style="width: 125px; height: 125px"></div>
<h2>100% Height</h2>
<div class="height" style="width: 50px; height: 200px"></div>
<div class="height" style="width: 200px; height: 50px"></div>
<div class="height" style="width: 125px; height: 125px"></div>
<h1>Centered</h1>
<h2>Cover</h2>
<div class="cover center" style="width: 50px; height: 200px"></div>
<div class="cover center" style="width: 200px; height: 50px"></div>
<div class="cover center" style="width: 125px; height: 125px"></div>
<h2>100% Height</h2>
<div class="height center" style="width: 50px; height: 200px"></div>
<div class="height center" style="width: 200px; height: 50px"></div>
<div class="height center" style="width: 125px; height: 125px"></div>
另外,如果你想剪裁图像使其以中心为焦点而不是左上角,请使用background-position: center;
。
img {
width: 100vw;
height: 100vh;
max-width: 100%;
max-height: 100%;
}