简体   繁体   English

溢出时延长百分比宽度

[英]Extend percentage width on overflow

I have the following html: 我有以下html:

<p style="margin:auto;border:solid 1px red;width:40%;">
<span style="white-space:nowrap;">a very long word i dont wont to break and this is very very very important</span>
</p>

I want the p tag to extend if the span needs it to be wider than 40% (like the example above) 如果跨度需要宽度大于40%,则我想扩展p标签(如上面的示例)

How can I do that? 我怎样才能做到这一点? (CSS solution is preferred if possible) (如果可能,最好使用CSS解决方案)

Use min-width instead of width . 使用min-width而不是width

<p style="margin:auto;border:solid 1px red;min-width:40%;">
<span style="white-space:nowrap;">a very long word i dont wont to break and this is very very very important</span>
</p>

If you use display: inline-block; 如果使用display: inline-block; as well, then the <p> will "shrinkwrap" itself to the width of its children: 同样, <p>会将自身“收缩”到其子级的宽度:

<p style="margin:auto;border:solid 1px red;min-width:40%;display:inline-block;">
<span style="white-space:nowrap;">a very long word i dont wont to break and this is very very very important</span>
</p>

Demo 演示

I used JavaScript for the solution, by checking if <p> is wider than its content area. 我通过检查<p>是否大于其内容区域来使用JavaScript作为解决方案。 I checked if the scrollWidth of <p> is larger than its clientWidth and if so I changed its width. 我检查了<p>scrollWidth是否大于其clientWidth ,如果是,则更改了其宽度。

Anat:I want to handle 2 different scenarios: (1) span with white-space:nowrap, and then I want the p to expand to the width of its child. Anat:我想处理2种不同的情况:(1)用white-space:nowrap扩展,然后希望p扩展到其子级的宽度。 (2)span can be without white-space:nowrap and then I want the width of p to be 40%. (2)span可以没有空白:nowrap,然后我希望p的宽度为40%。 The solution you offered only answers the first scenario. 您提供的解决方案只能解决第一种情况。

You want the style behaviour of one element to change depending on the style of another element. 您希望一个元素的样式行为根据另一元素的样式而改变。 I don't believe this is possible in CSS 2.1. 我认为CSS 2.1中不可能做到这一点。 The only way I can come up with, that will do what you want is to get rid of the span, and give the pa different class according to the different scenarios that you present. 我想出的唯一方法是,您要做的就是摆脱范围,并根据您呈现的不同场景为pa提供不同的类。 Scenario 1: text should be no-wrap and p should be as wide as required for the text: 方案1:文本应为不自动换行且p应与文本所需的宽度相同:

<p class="s1">

Scenario 2: 方案2:

should be no wider than 40% and text should wrap: 宽度不得超过40%,文字应换行:

<p class="s2">

Styles: 样式:

<style>
s1 {
 margin:auto;
 border:solid 1px red;
 white-space:nowrap;
 display:inline-block;
}
s2 {
 margin:auto;
 border:solid 1px red;
 width: 40%;
}
</style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM