CSS图像宽度基于高度,1:1比例

时间:2020-07-31 18:35:30

标签: css dynamic height width

我正在尝试根据浮动在图像右侧的文本内容,使图像的宽度/高度以1:1的比例与高度/宽度保持动态关系。

Flex框似乎与我要达到的目的相反,因为文本内容越多,它给该区域的空间就越少。

我在这里:https://jsfiddle.net/3sx7r40j/

.container {
  width: 350px;
  display: flex;
  flex-flow: row;
  align-items: stretch;
  border: 1px solid blue;
  margin-bottom: 25px;
}

.image {
  /** TODO Figure this css out **/
}

.image img {
  height: 100%;
  display: block;
  background: lightgrey;
}

.content {
  border: 1px solid yellow;
  font-size: 14px;
}
<div class="container">
  <div class="image">
    <img src="https://svgshare.com/i/NRA.svg">
  </div>
  <div class="content">
    Here is content that is only one line.
  </div>
</div>

<div class="container">
  <div class="image">
    <img src="https://svgshare.com/i/NRA.svg">
  </div>
  <div class="content">
    Here is the content that is even longer and longer and goes on two lines which the image on the left needs to be larger
  </div>
</div>


<div class="container">
  <div class="image">
    <img src="https://svgshare.com/i/NRA.svg">
  </div>
  <div class="content">
    Here is the content that is the longest and will continue on three lines or four lines etc... and the image needs to continue to grow based on the height of the content.
  </div>
</div>

这是当前状态的图像:

https://i.stack.imgur.com/mOzPL.png

这是期望的结果:

https://i.stack.imgur.com/UhRek.png

图像是SVG,其大小灵活。我知道可以使用JS来做到这一点,但我正在寻找一种纯CSS解决方案。

如果有更好的结构来使用flex box列,则div的结构是灵活的,因为它们似乎可以调整高度,但我不知道,我是flex box的新手。

1 个答案:

答案 0 :(得分:0)

我认为以下CSS代码将为您提供帮助

.container {
  width: 350px;
  display: flex;
  align-items:center;
  border: 1px solid blue;
  margin-bottom: 25px;
}

.image {
   background: lightgrey;
   height: 100%;
}

.image img {
  height: 100%;
  width:100%;
}

.content {
  border: 1px solid yellow;
  font-size: 14px;
  flex:1;
}
相关问题