html - 如何强制 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
解决方案
我建议你尝试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>
推荐阅读
- javascript - 制作一个 href=tel:无需添加号码即可工作
- asp.net - 构建网站会导致为该网站更改 IIS 文件夹
- terminal - Systemd 创建能够在全屏终端中显示自己的服务
- python - 使用 pyqtgraph 进行实时应用好不好?
- java - 如何在 Wildfly 12 服务器的standalone.xml 中配置 ETag 响应标头?
- java - 在 Spring Boot Context 路径之外访问 Swagger
- javascript - 如何在 Angular js 1.6 中使用 async:false,以便 java 脚本下一行执行被阻塞,直到 $http 完成
- javascript - 使用 REACT 在 div 中显示背景图像的问题
- node.js - 无法使用 webpack 加载 Node 原生插件
- powershell - 使用 powershell 将 bacpac 导出到 Azure 存储帐户