简体   繁体   中英

Make flex item siblings the same height

I have this simple example:

 .container { display: flex; background-color: #ddd; align-items: stretch; } .logo {} .text { font-size: 300%; } 
 <div class="container"> <div class="logo"><img src="https://upload.wikimedia.org/wikipedia/commons/0/07/Stora_Enso_web_logo.png" alt="test logo"></div> <div class="text">TEXT</div> </div> 

I need image to get same height as sibling div on right side not vv, ie shrink image to actual text height and keep aspect ratio.

How is one sibling supposed to know the height of another sibling? That's outside the scope of CSS. You'll need a script for that.

But both siblings can share equal height if they refer to the height of their parent.

This may not be what you want, but here's one potential solution:

 .container { display: flex; background-color: #ddd; height: 50px; } .logo { height: 100% } img { object-fit: contain; height: 100%; } .text { font-size: 300%; } 
 <div class="container"> <div class="logo"><img src="https://upload.wikimedia.org/wikipedia/commons/0/07/Stora_Enso_web_logo.png" alt="test logo"></div> <div class="text">TEXT</div> </div> 

Also see: One flex item sets the height limit for siblings

Use the same font-size value for the image height , but can't be % units.

 .container { display: flex; } .logo img { height: 3em; width: auto; } .text { font-size: 3em; } 
 <div class="container"> <div class="logo"><img src="https://upload.wikimedia.org/wikipedia/commons/0/07/Stora_Enso_web_logo.png" alt="test logo"></div> <div class="text">TEXT</div> </div> 

当您在父容器中指定display:flex ,通常可以通过指定父容器的固定高度并相应地设置子元素的大小来设置子元素的大小,其中flex-direction默认为@Michael_B建议row

 .container { display: flex; background-color: #ddd; height: 50px; } .logo { object-fit: cover; } .text { font-size: 300%; } img { height: 100%; display: block; } 
 <div class="container"> <div class="logo"><img src="https://upload.wikimedia.org/wikipedia/commons/0/07/Stora_Enso_web_logo.png" alt="test logo"></div> <div class="text">TEXT</div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM