当文本换行到两行时,块元素占用全部宽度

我基本上对此很好奇,因为我一直都在看,并且没有人跟我说过似乎知道是否有解决方案。

通常当我遇到它时,它是一个带有背景的花哨按钮,并且是显示块或内联块。

问题是这样的:假设你在一个div中有一个按钮,它有一个特定的宽度,比如说160px,并且你内部有一个显示块或者内嵌块,如果cant里面的文本全部适合它包装的一行两个像你所期望的,但现在它已经在两行上,它不再需要占据整个div的宽度,但它确实! 我真的不觉得奇怪,但是我想知道是否有人知道一个CSS或甚至JS解决方案可以解决这个问题?

码:

<div style="width: 160px; padding: 10px; background: blue;">
  <a href="#" style="background: red; display: block;">Test with a longwrappingword</a>
</div>

JSFiddle在这里


这对你有用吗?

<div style="width: 160px; padding: 10px; background: blue;">
  <a href="#" style="background: red; display: table; width: 1%">Test with a longwrappingword</a>
</div>
<span style="padding-left:130px">^ Where the element COULD end if it wanted to</span>

你是这个意思吗?

http://jsfiddle.net/UPxZm/

<div style="width: 160px; padding: 10px; background: blue;">
  <a id="block" href="#" style="background: red; display: block;">Test with a longwrappingword</a>
</div>

<script>
var $block = $('#block');
var orig = $block.html();
var index = orig.lastIndexOf(' ') || -1;
var longword = orig.substring(index + 1, orig.length);

$block.html(orig + longword);
var wanted_width = $block[0].scrollWidth / 2;
$block.html(orig);
$block.width(wanted_width);
</script>

你是这个意思吗? 我添加了一个宽度属性来锚定。

<div style="width: 160px; padding: 10px; background: blue;">
  <a href="#" style="background: red; display: block; width: 100px;">Test with a longwrappingword</a>
</div>
链接地址: http://www.djcxy.com/p/14283.html

上一篇: Block elements take full width when text wraps on to two lines

下一篇: Common Tooltip style in WPF