Not make centered text 100% width, CSS background only as wide as text

This article was written by in February 26, 2015, & may not be posted on other sites!
Original source url for this article: Not make centered text 100% width, CSS background only as wide as text

Not make centered text 100% width, CSS background only as wide as text.
Is your text block covering up the whole width, instead of just the text width? Are you trying to set a background color only as wide as text width, and not 100% width?

Not make centered text 100% width, CSS background only as wide as text

 

How to not make centered text 100% width, CSS background only as wide as text.

To have the text only as wide as itself, not 100% in width, use:
display: inline-block;
instead of
display: block;

display: inline-block;  will have the background only as wide as text.
display: block; -will have the background 100% of parent element width if a specific width is not set.

 

 

How to center the text, but keep css background only as wide as text

To center the text inside a div, set a background to the text, but still keep css background only as wide as text. Try this:

HTML
<div>
<h1 id="my-text">Heading</h1>
</div>


CSS
div{
text-align: center;
}
#my-text{

display: inline-block;
color: #ffffff;
background-color: #000000;
}

 

Spread the word

Facebooktwittergoogle_pluslinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *