首页 > 解决方案 > 如何强制 div 保持固定宽度但垂直扩展?

问题描述

我将图像放入 div 并将 div 的宽度设置为它包含的图像的宽度。例如:

<div class="img" style="width: 250px;">
<img src="thisIs250pxWide.jpg" alt="something">
<p>Caption text here, assume this text occupies more than 250px when it is all on one line</p>
</div>

问题在于,如果文本足够多,则将 div 拉伸得比指定的宽度更宽。我希望文本以指定的宽度行并垂直而不是水平拉伸 div - div 应该保持在图像的宽度,并且文本应该换行以同意它。滚动条是不可接受的,所以text-overflow无济于事。

如果有人将其称为与破坏单词的众多问题之一的重复,这与破坏单词无关。我什至不介意长词是否开箱即用 - 我只想在单词之间的空格处换行。

CSS是这样的:

div.img {
display: inline-block;
margin-left: 0.5em; margin-right: 0.5em;
border: 0.1em solid #111111;
padding: 0.4em;
}

我尝试在 div 之外添加 css:

<div class="img" id="imgDiv1234" style="width: 250px;">
<img src="thisIs250pxWide.jpg" alt="something">
<p>Caption text here, assume this text occupies more than 250px when it is all on one line</p>
</div>
<style type="text/css">#imgDiv1234 { width: 250px; }</style>

(这不能在样式表中完成,因为它特定于每个图像。)

还尝试过:将宽度放在<p>包含的 div 上;穿上!important风格;设置display: block而不是inline-block; 确保样式表中的任何内容都不会被否决。尽管如此,如果有足够的文本,div 会超出指定的宽度。

. . . .

编辑:如果它对任何人有帮助,在这次交流之后我发现了问题的原因,这是我的 CSP 标头:style-src 'self';- 这允许同域样式表但不允许内联样式。将其更改为以下内容可以使我的技巧起作用:style-src 'self' 'unsafe-inline';

这在理论上是不安全的,但攻击非常奇特,不适用于我的应用程序。绝对不允许使用unsafe-inline脚本或其他任何东西,但如果您研究并验证它在您的网站上不可利用,则样式可以是可以的。感谢 Eevee 和 Moog

标签: htmlcss

解决方案


我建议你尝试flex布局。它将简化您的代码,并且您不必width为每个块指定:

section {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start
}

figure {
  flex: 0 0;
  display: inline-flex;
  flex-direction: column;
  justify-content: flex-start;
  border: solid 1px;
  margin: .5em;
  padding: .4em
}
<section>

  <figure>
    <img src="https://picsum.photos/250/250" alt="something">
    <figcaption>Caption text here, assume this text occupies more than 250px when it is all on one line</figcaption>
  </figure>

  <figure>
    <img src="https://picsum.photos/150/150" alt="something">
    <figcaption>Caption text here, assume this text occupies more than 250px when it is all on one line</figcaption>
  </figure>
  
  <figure>
    <img src="https://picsum.photos/250/50" alt="something">
    <figcaption>Caption text here, assume this text occupies more than 250px when it is all on one line</figcaption>
  </figure>

</section>


推荐阅读