May 20, 2020

CSS: How to Set Background Color to be the Same Width of Text

It was when I needed to highlight a line of text that I stumble upon a simple knowledge of CSS on how to set background color to be the same width of text in a line. It's more a matter of taste rather than a necessity, since one can just set background color with the same width of the text container.

Ini!: CSS: Bagaimana Cara Membuat Background Color Selebar Tulisan

Taste of design is one the most visible differentiators between blogs, although without quality content it won't help blog owners to attract visitors. Still, if the cost is not that high, it's always good to make continuous improvements to blog's design however small they are.

The cost that blog owners should not spend with regard to blog design is that if it will sacrifice the speed of page loading rather significantly. Speed is one of the important factors that should always be in mind whenever having temptation to make changes to the current blog setting.

CSS How to Set Background Color to be the Same Width of Text

The simplest way to highlight a phrase is just using CSS background-color code, such as

CSS:
.hightlight{background-color:#555;color:#fff;padding:5px}

HTML:
<div class="highlight">How to Set Background Color</div>

How to Set Background Color

But, as you can see, the background color fills the width of the whole row.

There are a couple of ways when using CSS to set background color to be the same width of text, not the whole length of a row. The simplest one is using <span> instead of <div>, such as

CSS:
.hightlight{background-color:#777;color:#fff;padding:5px}

HTML:
<span class="highlight">How to Set Background Color</span>

How to Set Background Color

Other option is using, display: table;

CSS:
h1{display:table;background-color:#999;color:#fff;padding:10px;font-size:1em}

HTML:
<h1>How to Set Background Color</h1>

How to Set Background Color


Another option is using display: inline-flex;

CSS:
.hightlight{display:inline-flex;background-color:#222;color:#fff;padding:7px;font-size:1.2em}

HTML:
<div class="highlight">How to Set Background Color</div>

How to Set Background Color


There are a couple of more ways on how to set background color to have the same width of text but most on them are rather impractical. However, you may want to find it yourself out here.
Label: Blogger, CSS, WordPress
Bagikan ke: WhatsApp, Email. Print!.

aroengbinang, seorang penyusur jalan.
Traktir BA secangkir kopi? Scan via 'Bayar' GoPay.