craig1231
craig1231

Reputation: 3867

HTML - Centering DIV content

I am trying to span and center the content of div using class test1. Spanning the div across the full width of the page works. But centering the content in the div does not. What ever happened to using align=center simply?

<style>
    div.test1
    {
        width: 100%;
        margin-left: auto;
        margin-right: auto;
        text-align: center;
    }
    div.test2
    {
        display: inline;
        float: left;
    }
</style>

<div class="test1">
    <div class="test2">This</div>
    <div class="test2">Is</div>
    <div class="test2">A</div>
    <div class="test2">Test</div>
</div>

Upvotes: 5

Views: 9896

Answers (6)

Ian David Bocioaca
Ian David Bocioaca

Reputation: 107

Just put <center> before starting the div and </center> after closing the div. Like this:

<center>
    <div class="test1">
    <div class="test2">This</div>
    <div class="test2">Is</div>
    <div class="test2">A</div>
    <div class="test2">Test</div>
</div>
</center>

Upvotes: 2

A McGuinness
A McGuinness

Reputation: 88

Divs are block level elements. Spans are inline. Consider a larger div and span the smaller elements inside.

Upvotes: 0

Matt Coughlin
Matt Coughlin

Reputation: 18896

div.test1 {
    text-align: center;
}
div.test2 {
    display: inline-block;
    *display: inline; /* IE7 fix for inline-block */
    *zoom: 1;         /* IE7 fix for inline-block */
}

jsfiddle demo

Upvotes: 6

Saeed
Saeed

Reputation: 3775

You use css code :

.test1 .test2{
   width:100%;
   text-align:center;
 }

best regards

Upvotes: 0

Chris
Chris

Reputation: 26878

What ever happened to using align=center simply?

The align tag is deprecated. It wouldn't work in this case, anyway.

Use display: inline-block; instead of float: left; (and remove the display: inline; part, of course). Floated elements can not be centered.

Upvotes: 2

mr.soroush
mr.soroush

Reputation: 1130

try this:

<style>
    div.test1
    {
        width: 100%;
        margin-left: auto;
        margin-right: auto;
        text-align: center;
    }

</style>

<div class="test1">
    <div class="test2">This</div>
    <div class="test2">Is</div>
    <div class="test2">A</div>
    <div class="test2">Test</div>
</div>

Upvotes: 4

Related Questions