0

Hey guys im trying to center this:

<div class="title" align="center">
<h1>Welcome home, <?php echo ($_SESSION['username'])?>!</h1>
</div>

Here is the CSS im using:

.title{
position: absolute;
margin-left: auto;
margin-right: auto;
}

However its not working, it just stays in the upper right..

Thanks in advance!

  • 2
    how about `width:100%; text-align:center` - margin auto is not working because you're giving it an absolute position. – Kai Qing Aug 08 '14 at 22:35

5 Answers5

0

css absolute position won't work with margin-left:auto margin-right: auto

Community
  • 1
  • 1
Leeish
  • 5,203
  • 2
  • 17
  • 45
0

If you simply want to center the text in div, just use this:

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

You don't need position for that. See example:

http://www.cssdesk.com/UAEHe

The Krotek
  • 383
  • 1
  • 7
0

http://jsfiddle.net/VerdeletG/tfmkq8bL/

It's very simple. Just use

text-align:center 

for text. If you want to center content, then make a container with width:100% and margin:auto, and then the content should be centered. If not, experiment with positioning and widths along with padding and margins. Hope it helps!

Hayo Friese
  • 83
  • 10
0

When centering something responsively, there are two basic rules I follow:

a. For fluid elements

You have to set the width (usually percentage), and use text-align center. This also works for images inside an img tag.

<div>Text</div>

div {
    width: 100%;
    text-align: center;
}

b. For fixed-width elements

Margin auto only works when your elements has a fixed width and is relatively positioned

<div>Text</div>

div {
    width: 300px;
    margin: 0 auto;
    position: relative;
}

When you must use absolute positioning to center an element:

<div>This</div>

div {
    width: 300px;
    position: absolute;
    left: 50%;
    margin-left: -150px; /*half of width*/
}
Pau
  • 528
  • 1
  • 3
  • 10
0

I found using this works for centering a div within a div:

margin: 0;
position: absolute;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%); 

ref: https://www.w3.org/Style/Examples/007/center.en.tmpl

Wynn
  • 183
  • 1
  • 2