Stupid CSS Positioning Question

in Genius Bar edited January 2014
So I'm trying to learn CSS layout stuff (replace tables, yada yada, cool stuff). Anyway, I'm trying to make a class whose text is always centered on the page. Is this possible? I can say:

position: absolute;

left: 50%;

It's the closest I've gotten, but that lines up the left side of the text with the center of the window. And I can't seem to get around it by adding an align = "center" in my div tag either, which even if it worked, would be far less than ideal.

And I can't just use a text-align because I want a background behind the text. The full class is:



padding: 2px;

position: absolute;

text-align: center; /* Aligns within its own background. */

left: 10px; /* This is the line that I need to figure out. */

font-size: 8pt;

font-style: italic;

color: #AAAAAA;

background: #555555;

border: 1px solid #111111;


Any insight? Thanks.


  • Reply 1 of 6
    Wait, so you want text centered, and a background - is the background ONLY behind the text? I don't think I understand the problem.

    text-align: center; - that is right.

    then just put your background either in the <DIV> which surrounds the text, or the <P> to get it only behind the text?

    maybe post the relevant HTML also so I can understand better?
  • Reply 2 of 6


    though you might have to explain again what you're trying to achieve.
  • Reply 3 of 6
    Center-aligning elements in CSS is one area where it still sucks big time. \

    I have yet to find a method of centering that works *reliably* and efficiently in pure CSS.

    Best of luck. Just thought I'd share.
  • Reply 4 of 6
    Why could you not just do:


    position: absolute;


    margin-right: 20%;

    margin-left: 20%;

    You might have to play with the percentages some, but this should be re-workable to most layouts.
  • Reply 5 of 6
    fiddlerfiddler Posts: 36member
    I find the first method stupider..likeafox linked to to be the best method overall (the auto-margins). The negative left margin trick (the second link) works well to a point, but when the window is resized too small content gets pushed off the side of the page, with no scroll bars available effectively making the content unviewable.

    I'll also note that the negative margins trick is the ONLY way to *vertically* center elements on a page, at least as far as I know. It would seem auto vertical margins should work the same way as horizontal ones... but they don't. Don't ask why.

    What hurts even more is when you realize that IE Mac totally f*cks up this vertical centering method, making you put in stupid workarounds to cater to those who haven't moved to OS X/Safari..
  • Reply 6 of 6
    noleli2noleli2 Posts: 129member
    Thanks for all the tips. That should definitely help. Now that I'm done with finals I'll be able to play with it a bit more.
Sign In or Register to comment.