<img/>
实现与 background-image
相同的对齐?右上角的两个瓶子按照我想要的方式对齐:
<img/>
元素,而是
div
和
background-image
。
问题:右下角的两个瓶子使用了<img/>
元素(这就是我想要的),但它们的行为不一样。
我当然可以明确设置图像的宽度(如
50%
),但图像可能有不同的大小,或者可能有更多。因此我想避免显式设置宽度。
我该如何解决这个问题?别介意左边的图片。
代码如下:
.app {
padding: 5%;
}
.app > * {
max-width: 900px;
margin: 0px auto;
}
.box {
display: flex;
flex-direction: row;
flex: 1;
gap: 18px;
max-width: 100%;
max-height: 100%;
overflow: hidden;
border-radius: 18px;
background-size: cover !important;
background-repeat: no-repeat !important;
background-position: center !important;
}
.box.column {
flex-direction: column;
}
.box.hasBackground {
padding: 5%;
}
.box img {
object-fit: cover;
max-height: 100%;
max-width: 100%;
}
<div class="app">
<div class="box row hasBackground" style="background-image: linear-gradient(to top, rgb(250, 208, 196) 0%, rgb(255, 209, 255) 100%);">
<div class="box row ">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
</div>
<div class="box column ">
<div class="box row ">
<div class="box row hasBackground" style="background-image: url("https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg");"></div>
<div class="box row hasBackground" style="background-image: url("https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg");"></div>
</div>
<div class="box row ">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
</div>
</div>
</div>
</div>
就是这样,这里的技巧是使用
.app {
padding: 5%;
}
.app>* {
max-width: 900px;
margin-inline: auto;
}
.box {
display: flex;
flex: 1;
gap: 18px;
max-width: 100%;
max-height: 100%;
}
.box.column {
flex-direction: column;
}
.box.hasBackground {
padding: 5%;
}
.box img {
object-fit: cover;
height: 100%;
width: 100%;
aspect-ratio: 1;
border-radius: 18px;
}
<div class="app">
<div class="box row hasBackground" style="background-image: linear-gradient(to top, rgb(250, 208, 196) 0%, rgb(255, 209, 255) 100%);">
<div class="box row ">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
</div>
<div class="box column">
<div class="box row">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
</div>
<div class="box row">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
<img src="https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg">
</div>
</div>
</div>
</div>