The problem of css in the middle?

an element (out of the document stream, position:absolute), and the width of this element is not fixed, how can this element be centered horizontally? Is there any good solution?

Css
Mar.09,2021

use elastic layout. Parent element:
display: flex;
justify-content: center;// is centered horizontally
align-items: center;// is vertically centered

or
parent element:
position: relative;
Child element:
left: 50%;
top: 50%;
transform: translate (- 50%);


absolutely locate the child element, find the parent and element, and set the top left of the child element to 50%, transform:translate (- 50%);


width and height is just to make it easier to see the effect. You can take a look at my article centered on the n-middle method of a div .
div {
  position: absolute;
  width: 50px;
  height: 50px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: pink;
}

1. Flex layout:
parent element setting
.parent {

display: flex;
justify-content: center;
align-items: center;

}
2. Transform:transition (- 50% top: 50%)
position: absolute;
width: 100px;
height: 100px;
top: 50%;
left: 50%;
transform: translate (- 50% mam 50%);
/ / or write as
/ / margin-left:-50px; (to know the width and height of the element in advance)
/ / margin-right:-50px
3. Margin:0 auto (the easiest way to center horizontally, you need to know the element width)
4. Display:inline-block
parent element setting
.parent {

text-align: center;

}
child element setting
.child {

display:inline-block;

}


this is the horizontal and vertical center of your own arrangement. If compatibility allows, choose the one that best suits you
http://jsbin.com/cogiwid/70/e.

.
Menu