How do I make the background of an inline element with a line break extend to the farthest edge of each side?
I can't figure out how to do this even with containers. The background of the inline container will shrink to the size of each line, and the inline-block container will just act like a block element ... Floating doesn't work either.
Example:
<div style="width:250px;position:absolute;left:50%;top:50%;margin-left:-100px;border:2px solid #0000ff;">
<div style="display:inline-block;border:2px solid #ff0000;">
<p style="display:inline;background: #00ff00;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
http://codepen.io/anon/pen/zxKEBY
You can see that the inline-block container (red border) still fills the width of the shared container (blue border).
Is there a way to make the inline-block container only the width of the longest line of the inline element without setting the width explicitly?
source to share
I've searched for this for quite some time trying to figure out what's going on because it is very intriguing to me. And this is what I concluded:
The text actually runs to the edge as you can see, but by calling inline
it just presents the illusion that the container should be smaller because it made the word consectetr
go to the next line. A couple of things I noticed (I removed the inline CSS and added it to the CSS section of the JsFiddle for a better browsing experience):
ORIGINAL CODE: ORIGINAL FIDDLE
1. When set p
to inline-block
or inline
and adding, word-break: break-all
you can see that the word consectetr
fits perfectly into the box, just above the edge:
2. If you use your original code and change p
parent div
to inline
instead inline-block
, you can see the red border wraps around the text, but that doesn't wrap the container, it wraps the line of text, even breaking where that sentence is:
3. Finally, if you need to add a line break, the results will be as you'd expect:
So my final conclusion is that while it seems like the line is split into two different lines and is smaller than the parent's, this is just an illusion, and in fact it still occupies the full width of the parent, if only the tag <br/>
says, where to split the line.
source to share
There are two ways to accomplish this.
-
apply background to DIV, not P
-
Style p as shown below.
p {
display: inline-block;
width: auto;
background-color: #00ff00;
}
<div style="width:250px;position:absolute;left:50%;top:50%;margin-left:-100px;border:2px solid #0000ff;">
<div style="border:2px solid #ff0000;">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
Click here to see an example of where the div has a green background and not p
source to share