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 <a>
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, let's say 160px
, and you have a display block or inline-block <a>
inside, if the text inside the <a>
can't 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 JavaScript 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
Block-level ElementsA block-level element always takes up the full width available (stretches out to the left and right as far as it can). Two commonly used block elements are: <p> and <div> . The <p> element defines a paragraph in an HTML document.
To create a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows.
We use the word–break property in CSS that is used to specify how a word should be broken or split when reaching the end of a line. The word–wrap property is used to split/break long words and wrap them into the next line.
To do a line break in HTML, use the <br> tag. Simply place the tag wherever you want to force a line break. Since an HTML line break is an empty element, there's no closing tag. Below is an HTML file with a <p> and <br> element.
Does this work for you?
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With