Block elements take full width when text wraps on to two lines

I'm basically just curious about this because I see it all the time and no one I have spoken to seems to know if there is a solution.

Usually when I come across this its for a fancy looking button with a background on it and is display block or inline block.

The issue is this: say you have a button inside a div that has a specific width, lets say 160px, and you have a display block or inline-block inside, if the text inside the cant all fit on one line it wraps on to two as you would expect but now that it is on two lines it no longer really needs to take up the full width of the div but it does! I'm not really that surprised that this happens but I was wondering if anyone knew of a css or even JS solution that fixes this?

Code:

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

JSFiddle here


这对你有用吗?

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

Is this what you mean?

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>

Is this what you mean? I added a width attribute to anchor.

<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/14284.html

上一篇: 詹金斯电子邮件通知设置

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