Center Align on a Absolutely Positioned Div

后端 未结 9 414
攒了一身酷
攒了一身酷 2020-12-07 14:18
div#thing {
  position: absolute;
  top: 0px;
  z-index: 2;
  margin: 0 auto;
}

text text text with no fixed size, variable fon

相关标签:
9条回答
  • 2020-12-07 14:47

    I know I'm late to the party, but I thought I would provide an answer here for people who need to horizontally position an absolute item, when you don't know its exact width.

    Try this:

    // Horizontal example.
    div#thing {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
    

    The same technique can also be applied, for when you might need vertical alignment, simply by adjusting the properties like so:

    // Vertical example.
    div#thing {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
    
    0 讨论(0)
  • 2020-12-07 14:51

    If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:

    div#wrapper {
        position: absolute;
        width: 100%;
        text-align: center;
    }
    

    Remember that in order to position an element absolutely, the parent element must be positioned relatively.

    0 讨论(0)
  • 2020-12-07 14:53

    Or you can use relative units, e.g.

    #thing {
        position: absolute;
        width: 50vw;
        right: 25vw;
    }
    
    0 讨论(0)
提交回复
热议问题