TARKUS
TARKUS

Reputation: 2200

Need H2 to be only as wide as the text, but also text-align:center

I have two columns with H2 tags at the top of each column. The text in the H2 tags is short. The tags have a blue background. This is part of the problem, because as normal inline elements, the blue background will span the width of the div columns. Changing the H2 to display:inline-block will fix this, but that introduces another problem, that text-align:center no longer works, and the H2 tags will then align left.

How do I get an H2 element to both only be as wide as the text and align center?

<div style="width:auto;margin-left:auto;margin-right:auto;">
<h2 style="display:inline-block;background-color:#558ED5;color:#FFF;text-align:center;font-size:1.1em;padding:5px 10px 5px 10px;margin-left:auto;margin-right:auto;">WE OFFER 2 CLEANING OPTIONS:</h2>
</div>

Upvotes: 0

Views: 943

Answers (2)

Ahmed Salama
Ahmed Salama

Reputation: 2825

You should change the container div to text-align:center which will make h2 that has display:inline-block to be centered

<div style="width:auto;margin-left:auto;margin-right:auto;text-align:center">
<h2 style="display:inline-block;background-color:#558ED5;color:#FFF;text-align:center;font-size:1.1em;padding:5px 10px 5px 10px;margin-left:auto;margin-right:auto;">WE OFFER 2 CLEANING OPTIONS:</h2>
</div>

Upvotes: 1

Mukesh Ram
Mukesh Ram

Reputation: 6328

Add text-align:center; to main div. like this:

<div style="width:auto;margin-left:auto;margin-right:auto; text-align:center">
    <h2 style="display:inline-block;background-color:#558ED5;color:#FFF;text-align:center;font-size:1.1em;padding:5px 10px 5px 10px;margin-left:auto;margin-right:auto;">WE OFFER 2 CLEANING OPTIONS:</h2>
</div>

Upvotes: 2

Related Questions