Centering a percent-based div

前端 未结 6 1887
夕颜
夕颜 2020-12-13 18:23

Recently, a client asked that his site be percent-based rather than pixel-based. The percent was to be set to 80%. As you guys know, it is very easy to center the container

相关标签:
6条回答
  • 2020-12-13 18:36
    #container
    {
      width:80%;
      position:absolute;
      margin-left:-40%;
      left:50%;
    }
    

    or simply

    #container
    {
      width:80%;
      margin-left:10%;
    }
    
    0 讨论(0)
  • 2020-12-13 18:43

    I know it sounds crazy but how about getting the width in jQuery then resetting it so it is a pixel value?

    Or basing the width off the page width in jQuery?

    It's pretty weird he wants a percent based layout.

    Oh and last but not least, two 10% width divs surrounding it ;)

    0 讨论(0)
  • 2020-12-13 18:44
    position: absolute;
    width: 80%;
    left: 0;
    right: 0;
    margin: 0 auto;
    
    0 讨论(0)
  • 2020-12-13 18:48

    Remove the px value in the margin, just like this:

    #container { width: 80%; margin: 0 auto; }
    
    0 讨论(0)
  • 2020-12-13 18:53
    #container { width: 80%; margin: 0 auto; position relative; }
    

    And the element parent of "container" must be position relative or absolute

    for example:

    body{position:relative;}
    #container { width: 80%; margin: 0 auto; position relative; }
    
    0 讨论(0)
  • 2020-12-13 18:54

    The margin property supports percentage values:

    margin-left: 10%;
    margin-right: 10%;
    
    0 讨论(0)
提交回复
热议问题