Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS centering absolutely positioned elements with left: 50% and -33% left margin

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #172990
    mmcgu1966
    Participant

    I’ve seen (and used) a lot of examples of centering absolute positioning by using this method:

    position: absolute;
    left: 50%;
    margin-left: -100px; (half the element width))
    width: 100%;

    the obvious problem is in knowing the width of the element, which won’t work for dynamic-width elements.
    Recently, I started playing with using -33% left margin instead and this seems to center pretty well. Has anybody else tried this and/or see a problem with it?

    #173005
    Paulie_D
    Member

    There is a CSS3 alternative to

    margin-left: /* (half the element width) */
    

    It’s

    transform:translateX(-50%);
    

    If you need vertical center you can use transformY(-50%) in conjunction withtop:50%.

    Here’s a codepen where I use both combined into a single property

    transform:translate(-50%, -50%);
    

    http://codepen.io/Paulie-D/pen/BGkcr

    Support – http://caniuse.com/transforms2d

    #173041
    Kiran
    Participant

    Hi,

    You can center align a div horizontally and vertically by writing this code in css:

    #nameofdiv

    {Position: absolute;
    Left: 0;
    Right; 0;
    Bottom: 0;
    Top: 0;
    text-align: center;
    line-height: 50px;
    }

    Hope this will resolve your problem.

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘CSS’ is closed to new topics and replies.