need help CSS centering with absolute positioning

后端 未结 9 1201
庸人自扰
庸人自扰 2021-02-14 07:41

I\'ve never been totally satisfied with my various solutions to centering content in a web page. the

tag has been deprecated back in the middle of th
相关标签:
9条回答
  • 2021-02-14 08:03

    Don't you want relative positioning if 0,0 is going to be relative to a div?

    0 讨论(0)
  • 2021-02-14 08:04

    The easiest way:

    #element {
    
    position: absolute; /*Absolute Position*/
    
    top: 0; 
    left: 0;          /*Set the 4 coordinates to zero*/
    bottom: 0; 
    right: 0;
    
    margin: auto;      /*Margin to Auto*/
    
    height: 150px;   /*Set the Height and Width*/
    width:150px;
    
    background:green; /* Backgroung:optional*/
    

    }

    This will bring it right at the middle, no matter it's size.

    Hope that helps!

    See Fiddle: http://jsfiddle.net/kfPC6/

    0 讨论(0)
  • 2021-02-14 08:04

    maybe I didn't understand the task but I think you can use

    margin: 0 auto;
    

    for centering your divs

    0 讨论(0)
  • 2021-02-14 08:07

    I nice way to center stuff is to use the "margin:auto" css tag. This works in FF and Safari. Just give a div some width and a margin auto, and if the parent is 100% width, then this div will center align itself.

    For this to work in IE, you have to use the text-align:center attribute on the parent and then text-align left on the actual centred div.

    AFAIK, there is no way to change the absolute co-ordinates from 0,0 to some other arbit point. Relative is the way to go.

    0 讨论(0)
  • 2021-02-14 08:12

    Use relative positioning on the parent and give that same element the property:

    margin: 0 auto;
    

    The parent is now positioned and you should be able to set elements absolutely within it.

    Example:

    div#page{
      position:relative;
      width:400px;
      margin:0 auto;
    }
    
    div#page #absoluteExample{
      position:absolute;
      top:18px;
      left:100px;
    }
    
    0 讨论(0)
  • 2021-02-14 08:14

    The text-align: center; property does what <center> used to and it is vastly superior to it.

    Only thing is, it's a bit more complex to use. Once you get the hang of it, you'll wonder why you were having so much trouble before!

    You must use it in coordination with the properties of other elements on the page. That is the issue developers/designers have with CSS and newer HTML technologies. It gives us a powerful way to present our page elements but makes it much more complex and strict.

    Mike Robinson's answer certainly solves the problem you're having here and it's a great example. But...

    I don't think any one answer will show you how to use text-align properly for all cases you'll come across but try looking into how positioning in CSS works more in-depth.

    0 讨论(0)
提交回复
热议问题