The first method is to first use margin:0 Auto to center horizontally, then set position:relative, set top to 50% (parent element height of 50%), and then set margin-top:-150px (negative value is set because you want to move the div up, 150px is the height of the div), the code is as follows:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Index</title> <style>Html,body{width:100%;Height:100%;margin:0;padding:0; }. Content{width:300px;Height:300px;background:Orange;margin:0 Auto; /*Center Horizontally*/position:relative;Top:50%; /*Offset*/Margin-top:-150px; } </style></Head><Body> <Divclass= "Content"></Div></Body></HTML>
The implementation results are as follows:
Because the div has a height, you can assign overflow:auto to it so that if there is too much content in the Div, the scroll bar appears. The point of this approach is that you can use not so many nested tags, but also for all browsers, the downside is that if the browser window shrinks to a certain extent, the div disappears
The second method: On the basis of the above method, in addition to setting the margin-top upward move, you can also set the CSS3 Transform property can also implement this function, by setting the Div transform:translatey (-50%), This means that the div pans upward (translate) by half of its height (50%), the code is as follows:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Index</title> <style>Html,body{width:100%;Height:100%;margin:0;padding:0; }. Content{width:300px;Height:300px;background:Orange;margin:0 Auto; /*Center Horizontally*/position:relative; Top:50%; /*Offset*/Transform:Translatey ( -50%); } </style></Head><Body> <Divclass= "Content"></Div></Body></HTML>
The third way: with CSS3 's flexible layout (flex), the problem becomes much easier. Using CSS3 's elastic layout is simple, as long as the display value of the parent element (this is the body) is flex.
The code is as follows:
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Index</title> <style>Html,body{width:100%;Height:100%;margin:0;padding:0; }Body{Display:Flex;Align-items:Center; /*the element that defines the body is centered vertically*/justify-content:Center; /*defines the horizontal center of the element inside the body*/ }. Content{width:300px;Height:300px;background:Orange; } </style></Head><Body> <Divclass= "Content"></Div></Body></HTML>
CSS Vertical centering method (i)