如何防止图像放大单元格在flexbox CSS [重复]

8zzbczxx  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(218)

此问题已在此处有答案

How to match width of text to width of dynamically sized image/title?(2个答案)
7天前关闭
Flexbox父宽度应由child1中的文本决定。child2中图像应随父级的增长而增长。父div应该增长到最大宽度,但当我把我的图像里面,它扩大了我的父。

#parent {
  display: flex;
  flex-direction: column;
  min-width: 10px;
  max-width: 240px;
}
<div id="parent">
  <div id="child1">text here should decide parent width</div>
  <div id="child2"><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>
5vf7fwbs

5vf7fwbs1#

快速,为了说明我的评论如何防止图像放大单元格在flexbox的CSS,但必须有关于这一点重复

.parent,
#parent {
  display: flex;
  flex-direction: column;
  min-width: 10px;
  width:max-content;
  max-width: 240px;
  border: solid;
}

.parent img,
#parent img {
  width: 0;
  min-width: 100%;
}
<div id="parent">
  <div id="child1">text here should decide parent width</div>
  <div id="child2"><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>

<div class="parent">
  <div>t</div>
  <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>

<div class="parent">
  <div>text</div>
  <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>

<div class="parent">
  <div>text here</div>
  <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>
<div class="parent">
  <div>text here should </div>
  <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>
<div class="parent">
  <div>text here should decide parent width . IS that clear?</div>
  <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>
sg3maiej

sg3maiej2#

<style>
#parent {
  display: flex;
  flex-direction: column;
  min-width: fit-content;
  max-width: 240px;
}

#child1 {
  word-wrap: break-word; 
}

#child2 {
  flex-grow: 1; 
}

#child2 img {
  width: 100%; 
  height: auto; 
}
</style>

<div id="parent">
  <div id="parent">
  <div id="child1">text here should decide parent width</div>
  <div id="child2"><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>
</div>

如果您希望文本在达到父级的最大宽度后换行到下一行=更新=

#parent {
  display: flex;
  flex-direction: column;
  min-width: fit-content;
  max-width: 240px;
}

#child1 {
  word-wrap: break-word; 
}

#child2 {
  flex-grow: 1; 
}

#child2 img {
  width: 100%; 
  height: auto; 
}

以下是HTML更新:

<div id="parent">
  <div id="child1">text here should decide parent width</div>
  <div id="child2"><img src="https://picsum.photos/400/100" alt="Image" /></div>

我希望这对你有帮助。
===更新网格===

<style>
#parent {
  display: grid;
  grid-template-columns: min-content 1fr;
  min-width: fit-content;
  max-width: 240px;
}

#child1 {
  word-wrap: break-word; 
}

#child2 {
  width: 100%; 
}

#child2 img {
  width: 100%; 
  height: auto; 
}
</style>

</head>
<body>

<div id="parent">
  <div id="child1">text here should decide parent width</div>
  <div id="child2"><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>

相关问题