I want to have a background color on an inline-block element that doesn't go past the widest point of text. It works fine as long as the line break in the text is explicit by adding a <br>
tag. If there's no <br>
tag and it wraps on its own, it goes to 100% width.
Here it is with the <br>
tag after "ipsum".
And here it is when it wraps on its own:
https://jsfiddle.net/340v3hnj/
How can I have the background be the size of the text box without having to manually add <br>
tags?
.wrapper {
border: 1px solid red;
text-align: center;
width: 450px;
}
p {
display: inline-block;
margin: 0;
padding: 10px;
font: 50px arial;
color: white;
background: black;
width: auto;
}
<div class="wrapper">
<p>Lorem ipsum dolorsit amet</p>
</div>
If you have a border or padding set for your divs, then you've created additional pixels that will prevent your divs from adding up to a 100% width. To fix this, make sure you've added box-sizing: border-box to the div's styles.
By default, a block level element takes up the entire width of its parent container. After it's reached the edge of the container it'll drop below the other elements. So, even if you only have one paragraph in the <body> then it will still take up the entire width of the browser.
As a result, the elements can sit next to each other. The major difference between display: inline; and display: inline-block; is that, display: inline-block; also allows us to set the width and height of the element. We can prevent inline-block divs from wrapping by adding suitable Bootstrap classes.
Inline elements are built for text and thus they should flow inline with the text, and only be as wide as the text they contain. Thus, you can't set the width of an inline element. Block elements are made to fill all the available width by default and are thus on their own line rather than flowing inline.
Please check if this works.
<p>
tag will produce broken background effect line-by-line for the paragraphHope this works for you!
.wrapper {
border: 1px solid red;
text-align: center;
width: 450px;
}
p {
display: inline-block;
padding: 10px;
font: 50px arial;
color: white;
background: black;
/* try adding the following line to your code */
margin: 0 60px;
}
<div class="wrapper">
<p>Lorem ipsum dolorsit amet</p>
</div>
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