Make flex item siblings the same height

怎甘沉沦 提交于 2021-02-10 12:20:08

问题


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, i.e. shrink image to actual text height and keep aspect ratio.


回答1:


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




回答2:


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>



回答3:


When you specify display:flex in the parent container generally the child elements can be sized by specifying a fixed height of the parent container and setting the child elements accordingly with a flex-direction default being row as @Michael_B suggested.




回答4:


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


来源:https://stackoverflow.com/questions/52615329/make-flex-item-siblings-the-same-height

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!