【问题标题】:CSS Image Width based on Height, 1:1 ratioCSS 图片宽度基于高度,1:1 比例
【发布时间】:2020-11-21 15:01:28
【问题描述】:

我试图弄清楚如何根据浮动到图像右侧的文本内容使图像宽度/高度达到 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)​​文本将定义高度(2)图像高度将适合它(3)图像的宽度将改变(4)宽度的改变将改变文字宽度(5)文字高度会改变,我们回到(1)--->无限循环
  • @TemaniAfif - 你可能是对的,只是想看看是否有一些 CSS 专家可以看看我是否遗漏了什么。

标签: css dynamic height width


【解决方案1】:

我认为下面的 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;
}

【讨论】:

  • 事情是高度和宽度是基于文本长度什么推动容器有更大的高度。查看所需的结果图像。
猜你喜欢
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 2020-10-10
  • 1970-01-01
相关资源
最近更新 更多