javascript - 如何将图像适合 div?
问题描述
我在尝试将图像放入我的 div 时遇到问题。我的图像比我的 div 大,所以当我做传统的
style="width:100%;"
它将调整 div 的大小,占用比应有的空间更多的空间。
我试过使用 style="max-width:100%;" 背景尺寸:包含;背景尺寸:封面;
以及几乎所有调整图像大小以适应整个 div 的方法。
我正在使用 CSS 网格,因此该区域的大小是我希望保持整个图像适合的方式,但是当使用诸如 max-width 之类的东西时,它只会改变区域的大小,使其大于它应该是
我基本上想做类似的事情
图像将占据整个 div 而不会溢出的位置
解决方案
我快速创建了以下 CSS 网格,它看起来像您想要演示的结果。我还添加了一些你可以用 CSS 网格做的很酷的技巧。
body, html{
margin: 0;
padding: 0;
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
.container{
margin: 0 auto;
width:100%;
height: 100vh;
display:grid;
grid-template-columns: 5% repeat(3, 1fr) 5%;
grid-template-rows: 5% repeat(2,1fr) 5%;
grid-gap: 1%;
}
.imageOne{
grid-row: 2/3;
grid-column: 2 / -2;
background-color:rgb(247,247,247);
background-image:url('https://cdn.photographylife.com/wp-content/uploads/2016/06/Mass.jpg');
background-repeat:no-repeat;
background-size: 100% 100%;
background-position:center;
color:rgb(255,255,255);
}
.imageTwo{
grid-row: 3/4;
grid-column:2 / 3;
background-image:url('https://cdn.photographylife.com/wp-content/uploads/2016/06/Mass.jpg');
background-repeat:no-repeat;
background-size: 100% 100%;
background-position:center;
color:rgb(255,255,255);
}
.imageThree{
grid-row: 3/4;
grid-column:3 / 4;
background-image:url('https://cdn.photographylife.com/wp-content/uploads/2016/06/Mass.jpg');
background-repeat:no-repeat;
background-size: 100% 100%;
background-position:center;
color:rgb(255,255,255);
}
.imageFour{
grid-row: 3/4;
grid-column:4 / 5;
background-image:url('https://cdn.photographylife.com/wp-content/uploads/2016/06/Mass.jpg');
background-repeat:no-repeat;
background-size: 100% 100%;
background-position:center;
color:rgb(255,255,255);
}
<div class="container">
<div class="imageOne">
image one
</div>
<div class="imageTwo">
image two
</div>
<div class="imageThree">
image three
</div>
<div class="imageFour">
image four
</div>
</div>
享受并希望它有所帮助。还有 Codepen 链接在这里