InfiniteLoop InfiniteLoop - 6 months ago 9
CSS Question

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>

Answer

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>
Comments