我将图像放入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拉伸得比指定宽度宽。我希望文本以指定的宽度 wrap 并垂直而不是水平地拉伸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
用于脚本或其他任何内容,但是如果您研究并确认它无法在您的网站上使用,则可以使用样式。谢谢伊芙和穆格
答案 0 :(得分:1)
我建议您尝试使用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>
答案 1 :(得分:0)
使用max-width属性与您一样设置所需的最大值
ajax.core