Use position to generate absolutely positioned elements
absolute
Generates an absolutely positioned element, positioned relative to the first parent element other than static positioning.
The position of the element is specified by the "left", "top", "right" and "bottom" attributes.
fixed
Generates absolutely positioned elements, positioned relative to the browser window.
The position of the element is specified by the "left", "top", "right" and "bottom" attributes.
How to center an element
method one
For known width and height, margin can be used
.box{
width:600px;
height:300px;
position:absolute;
/*position:fixed;*/
left:50%;
top:50%;
margin-left:-300px;/*宽度的一半*/
margin-top:-150px;/*高度的一半*/
}
or use
margin:auto;
Method Two
Using transform in css3, both unknown width and height and known width and height can be used
1. Center horizontally
.box{
width:auto;
height:40px;
padding:20px;
position:absolute;
top:50px;
left:50%;
transform:(-50%,-50%);
}
2. Center both horizontally and vertically, change the above top to
top:50%;