Center div
An absolutely positioned element acts the same for the distribution of free space, and similarly can be centered vertically at the specified top and bottom.
The trick of aligning div in the center: (The best and most flexible way example code).
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div1 {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
</head>
<body>
<div id="div1"></div>
</body>
</html>Output:

Note: only works if your element has a fixed height.
How to horizontally center a <div>
With flex-box, it is very easy to style the div horizontally and vertically centered in HTML.
To align the div vertically centered also, use property align-items: center.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#outer {
border: 1px solid red;
width:100%
display: flex;
justify-content: center;
}
#inner {
border: 1px solid black;
}
</style>
</head>
<body>
<div id="outer">
<div id="inner">Foo foo</div>
</div>
</body>
</html>Output:

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version