Ken
Ken

Reputation: 57

Center Elements Inside of a Div

I have a div where the elements need to be centered:

<div style="width:800px;margin:0 auto;color:#000;"><h3 style="float:left;color:#000;margin:0 10px;"> Test </h3><h4 style="float:left;padding-top:3px;"> | </h4><h3 style="color:#000;float:left;margin:0 10px;"> Test </h3></div>

However, the elements all just stay to the left. How do I fix this and center all the h3's and h4's?

Here is my example: http://approvemyride.ca/reno/

Upvotes: 0

Views: 4482

Answers (2)

user710031
user710031

Reputation:

http://jsfiddle.net/ZeJdc/

HTML:

<div>
    <h3> Test </h3>
    <h4> | </h4>
    <h3> Test </h3>
</div>

CSS:

div {
    width: 800px;
    margin: 0 auto;
    color: #000;
    text-align: center;
}

h3 {
    color: #000;
    margin: 0 10px;
    display: inline-block;
}

h4 {
    padding-top: 3px;
    display: inline-block;
}

Check that out and let me know what you think, if it doesn't look centered when you first open it try stretching the little divider to the left to give the results pane more room.

To clarify, display:inline-block is what's allowing all the headers to be displayed on the same line while text-align:center is what's centering all of your header elements inside the <div>.

Upvotes: 2

mshsayem
mshsayem

Reputation: 18028

Whenever I face any floated container to center horizontally I use the followings. Try wrapping your markup (which needs to be centered; the div in your case) with these:

<div class="center_outer">
    <div class="center_inner">
        <!-- Put your contents here (which needs to be centered) -->
    </div>
</div>

CSS:

.center_outer
{
    position: relative;
    left: 50%;
    float: left;
}
.center_inner
{
    position: relative;
    left: -50%;
}

Check: http://jsfiddle.net/jduDD/1/ (I have removed the width style)

Upvotes: 0

Related Questions