Apply background color to the width of the text and center it

Viewed 453

When I apply background color to a text and try to center it, the background color takes up the whole webpage's width. I wanted the bg color to take up the text's size only.

HTML

<div class="order">
    <h3>Hello world</h3>
    <h1>How are you doing</h1>
</div>

CSS

.order h3,
.order h1, {
text-align: center;
}

.order h3 {
display: inline-flex;
font-family: Raleway;
color: white;
background-color: var(--main-color);
}

.order h1 {
  font-family: Raleway;
 }
2 Answers

Try the below code (using flexbox):

.order {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.order h3 {
  font-family: Raleway;
  color: white;
  background-color: blue;
}

.order h1 {
  font-family: Raleway;
  background-color: blue;
}
<div class="order">
    <h3>Hello world</h3>
    <h1>How are you doing</h1>
</div>


You can adjust the background-color and add it where needed.

This is what the <span> tag is designed for.

.order {
    text-align: center;
}

.order h3 > span {
    font-family: Raleway;
    color: white;
    background-color: blue;
}

.order h1 > span {
  font-family: Raleway;
  color: white;
  background-color: blue;
}
<div class="order">
    <h3><span>Hello world</span></h3>
    <h1><span>How are you doing</span></h1>
</div>

As described by w3schools.com;

The <span> tag is an inline container used to mark up a part of a text, or a part of a document.

The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute.

The <span> tag is much like the <div> element, but <div> is a block-level element and <span> is an inline element.

Related