我有一个宽度为97%、高度为100vh的div,用于将div的高度与窗口高度相匹配。这很有效。
现在我想在这个div中放置一个图像。这个图像应该填充div的宽度,但不能超过图像高度允许的宽度,而不会溢出、被剪切或拉伸。
这是我的html代码:
<!DOCTYPE html>
<html>
<body>
<div>
<p class="title">This is a title!</p>
<img src="https://via.placeholder.com/800x600.png">
</div>
</body>
</html>
我试过这个css:
img {
max-width:90%;
margin-bottom:5px;
}
div {
border-style:solid;
border-width:1px;
width:97%;
height:100vh;
}
但这不会将图像扩展到超过800px的宽度。所以这不会填满分区的宽度。
我试过这个css:
img {
width:90%;
margin-bottom:5px;
}
div {
border-style:solid;
border-width:1px;
width:97%;
height:100vh;
}
但是图像会垂直溢出。
我该怎么做?
不要使用img,而是为div设置背景示例:
<!DOCTYPE html>
<html>
<body>
<div>
<p class="title">This is a title!</p>
</div>
</body>
</html>
div {
width:97%;
height:100vh;
background-image: url("https://via.placeholder.com/800x600.png");
background-size: cover;
}
您可以使用:
div {
border:1px solid #000;
border-width:1px;
width:97%;
height:100vh;
}
p {margin:0;}
img {
display:block;
width:100%;
height:calc(100% - 18px);
object-fit:contain;
object-position:top; /*or object-position:left top; if you want the image aligned to left*/
}
<div class="container">
<p class="title">This is a title!</p>
<img src="https://via.placeholder.com/800x600.png">
</div>
已编辑
这就是解释您需要的东西的方式:(文本已删除,逻辑错误(。。。
更新
你至少要欣赏我的毅力。。。
"Flexbox Layout"机制的默认值起到了作用。
- 父级
.wrapper
div需要为display: flex
,因为默认情况下FBL子元素具有flex-grow: 0
,这可以防止图像在父级之外生长 - 让
.wrapper
通过align-items: flex-start
(而不是默认的stretch
(将内容拉到其一侧 - 默认情况下,
img
具有width: auto; height: auto
,因此只有height: 100%
会导致图像在保持其比例的情况下增大大小 - 设置其
max-width: 100%
将使其保持在父级中(与默认的flex-grow: 0
结合使用( object-fit: contain
将确保合适的比例object-position: 0 0
将把图像附加到其内容框的左上角(与默认的center
或50% 50%
相反(。您可以通过禁用CSS来测试这一点,因为您可能更喜欢默认的CSS
结果是图像根据其高度和比例调整大小,附加到文本并停留在父容器内。没有切割,剪裁,没有比例拉伸,没有溢出,什么都没有。。。没有JS。。。
.wrapper {
display: flex;
flex-direction: column; /* a column of 2 rows (text and image)*/
align-items: flex-start; /* horizontal align (default = 'stretch') */
border-style: solid;
border-width:1px;
width : 97%;
height: 100vh;
}
.img {
height: 100%; /* always full height image (default is 'width: auto') */
max-width: 100%; /* don't go outside parent container */
/* max-height: calc(100% - 50px); /* don't go outside parent container */
/* only required when '.wrapper' has no 'align-items: flex-start' */
object-fit: contain; /* no cutting or stretch */
object-position: 0 0; /* move to top/left postion of content box (default is center) */
}
<div class="wrapper">
<p class="title">This is a title!</p>
<img class="img" src="https://via.placeholder.com/800x600.png">
</div>