在 Flexbox 中对齐图像(适用于背景图像,但不适用于 <img/>)

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

如何使用
<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(&quot;https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg&quot;);"></div> <div class="box row hasBackground" style="background-image: url(&quot;https://velgnorsk.no/wp-content/uploads/2020/01/Ocean-bottle_VN_marinebla%CC%8A.jpg&quot;);"></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>

就是这样,这里的技巧是使用
html css flexbox alignment
1个回答
0
投票
,我做了其他调整,请参阅下面的代码片段

.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>

© www.soinside.com 2019 - 2024. All rights reserved.