Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap background color around text aligned right

Tags:

What I'm trying to do:

I'm trying to achieve the following result:

div {
  text-align: right;
}

span {
  display: inline-block;
  background: #000;
  color: #fff;
}
<div>
  <span>abc</span><br/>
  <span>Hello world this is some text</span><br />
  <span>hello world</span>
</div>

However, in the above example, I have split my lines up individually, as I have contained each line in a separate span.

I want to achieve the same (or similar) result as above by using a width to define when a new line should start/end, rather than containing each new line in its own span.

What I've tried:

I've tried doing the following:

div {
  text-align: right;
}

span {
  display: inline-block;
  background: #000;
  color: #fff;
  width: 200px; /* Width to define where line break should appear */
}
<div>
  <span>abc</span><br/>
  <span>Hello world this is some text hello world</span>
</div>

However, in the above example, the black background covers a "block" rather than wrapping around each line of text.

So, how do I get my second snippet to act in the same way as the first?

like image 687
Nick Parsons Avatar asked Nov 22 '18 00:11

Nick Parsons


1 Answers

Add another wrapper that you keep inline:

div {
  text-align: center;
}

span {
  display: inline-block;
  line-height:1; /*remove the gap*/
  color: #fff;
  width: 200px; /* Width to define where line break should appear */
}
span > span {
  display:inline;
  background: #000;
}
<div style="text-align: right;">
  <span><span>abc</span></span><br>
  <span><span>Hello world this is some text hello world</span></span>
</div>

You can also adjust padding and keep the default line-height:

div {
  text-align: center;
}

span {
  display: inline-block;
  color: #fff;
  width: 200px; /* Width to define where line break should appear */
}
span > span {
  display:inline;
  background: #000;
  padding:2px 0;
}
<div style="text-align: right;">
  <span><span>abc</span></span><br>
  <span><span>Hello world this is some text hello world</span></span>
</div>
like image 140
Temani Afif Avatar answered Sep 22 '22 20:09

Temani Afif