当文本换行到两行时,块元素占据全宽

问题描述 投票:8回答:3

我基本上只是对此感到好奇,因为我一直看到这一点,而且我所说过的任何人似乎都不知道是否有解决方案。

通常当我遇到它时,它看起来像一个看起来很奇怪的<a>按钮,背景就是显示块或内联块。

问题是这样的:假设你在div中有一个具有特定宽度的按钮,让我们说160px,你有一个显示块或内嵌块<a>里面,如果<a>内的文字不能全部适合一行它像你期望的那样包装到两个但是现在它在两条线上它不再需要占用div的全宽,但确实如此!

我发现这种情况并不奇怪,但我想知道是否有人知道CSS甚至JavaScript解决方案可以解决这个问题?

码:

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

JSFiddle here

text width line block
3个回答
2
投票

this能为你工作吗?

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

1
投票

你是这个意思吗?

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>

0
投票

你是这个意思吗?我为锚点添加了一个width属性。

<div style="width: 160px; padding: 10px; background: blue;">
  <a href="#" style="background: red; display: block; width: 100px;">Test with a longwrappingword</a>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.