Maurice
Maurice

Reputation: 1157

How to center my <h3> text using css?

I have the following fiddle

The HTML is created by javascript. I can add/change the styles to the div's if needed but I cannot change the order of the HTML code.

I know I can use:

text-align: center;

But there is a catch :) The div containing the 4 images is put in the HTML code before the <h3> is. Since I cannot edit the HTML order I figured to lower the DIV with the images using margin-top: 70px; The problem is that this has an effect on the text in the <h3> which isn't centered anymore.

How to solve this? (pref with css3)

It's okay if the values of the DIV's in the HTML need to be changed in order to fix it (I can change them)

Thanks a lot

The HTML code:

<div class="solitaireprefs" style="position: absolute; left: 0px; top: 0px; width: 80%; height: 80%; z-index: 100;">
<form method="get" action="">
    <div style="float: right; margin-top: 70px; display: table; vertical-align: bottom;">
        <div><img src="cardsets/test/spades1.svg" alt="Ace spades" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"><img src="cardsets/test/clubs7.svg" alt="7 clubs" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"></div>
        <div><img src="cardsets/test/hearts12.svg" alt="Queen hearts" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"><img src="cardsets/test/backred.svg" alt="Card" align="bottom" style="vertical-align: bottom; width: 119px; height: 166px;"></div>
    </div>
    <h3>Options</h3>
    <h4>Images for size 119</h4>
</form>
</div>

The CSS:

div.solitaireprefs {
    background-color: #fff;
    border-radius: 7px; 
    border: 1px solid #ddd;
}

div.solitaireprefs form {
    padding: 0 15px;
}

div.solitaireprefs h3 {
    background: #e9e9e9;
    margin: 0 -15px;
    padding: .7em 0;
    text-align: center;
    border-radius: 7px 7px 0 0 ; 
}

Upvotes: 7

Views: 33556

Answers (2)

KatieK
KatieK

Reputation: 13843

Instead of float:right; and margin:top on the element that contains the images, position it absolutely.

{ position: absolute;
  top: 70px; 
  right: 10px;
}

Using absolute positioning takes it out of the flow of the document; which is what is messing up the centering on your h3.

Upvotes: 2

Andrew
Andrew

Reputation: 794

The real answer to the question is to figure out how you can arrange the dom elements correctly. Semantics is more important than you think. But since you are already kinda hacking the visuals, the quickest and dirtiest hack is to fix your padding:

padding: .7em 45%;

on the div.solitairprefs h3 Tweak the percentage to get the middle, but the missing 10% of the sum of left and right padding on the h3 is the space between where the options text appears (so tweak accordingly). And since you're already manually centering, you can go ahead and get rid of the

text-align: center;

Upvotes: 4

Related Questions