Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline-block element extends to 100% width when wrapping lines

Tags:

html

css

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>
like image 669
Gavin Avatar asked Jan 21 '17 18:01

Gavin


People also ask

How do inline-block elements add up to 100% width?

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.

Do block elements span the entire width?

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.

How do you prevent inline-block elements from wrapping?

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.

How do I increase the width of an inline-block?

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.


1 Answers

Please check if this works.

  • trying inline attributes inside <p> tag will produce broken background effect line-by-line for the paragraph
  • Since you have mentioned that width cannot be kept fixed, so margins from the container edges have been handled

Hope 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>
like image 135
Ritika Gupta Avatar answered Nov 15 '22 00:11

Ritika Gupta