开发者

Extend percentage width on overflow

开发者 https://www.devze.com 2023-01-23 13:20 出处:网络
I have the following html: <p style=\"margin:auto;border:solid 1px red;width:40%;\"> <span style=\"white-space开发者_JS百科:nowrap;\">a very long word i dont wont to break and this is ver

I have the following html:

<p style="margin:auto;border:solid 1px red;width:40%;">
<span style="white-space开发者_JS百科: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)

How can I do that? (CSS solution is preferred if possible)


Use min-width instead of 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; as well, then the <p> will "shrinkwrap" itself to the width of its children:

<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. I checked if the scrollWidth of <p> is larger than itsclientWidth and if so I changed its width.


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. (2)span can be without white-space:nowrap and then I want the width of p to be 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. The only way I can come up with, that will do what you want is to get rid of the span, and give the p a different class according to the different scenarios that you present. Scenario 1: text should be no-wrap and p should be as wide as required for the text:

<p class="s1">

Scenario 2:

should be no wider than 40% and text should wrap:

<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消