/* Assume the div has a class of "center"
The below would center it horizontally
*/
.center {
margin-left: auto;
margin-right: auto;
}
/* There is a shorthand and it is given below */
.center {
margin: 0 auto;
}
<!--center text-->
<!--padding deals with margins within the element itself-->
<!--margin deals with blank space surrounding and element-->
<!DOCTYPE html>
<html>
<head>
<style>
.center {
margin: auto;
width: 80%;
border: 3px solid #73AD21;
padding: 10px;
margin: 20px;
}
</style>
</head>
<body>
<h2>Center Align Elements</h2>
<p>To horizontally center a block element (like div), use margin: auto;</p>
<div class="center">
<p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
.center {
margin: auto;
width: 80%;
border: 3px solid #73AD21;
padding: 10px; # deals with margins within the element itself
margin: 20px; # deals with area around outside of element
}
</style>
</head>
<body>
<h2>Center Align Elements</h2>
<p>To horizontally center a block element (like div), use margin: auto;</p>
<div class="center">
<p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p>
</div>
</body>
</html>
{{-- this is my code
there is two ways to do it
the first method using flex box
--}}
<html>
<body>
<style>
.center {
display: flex;
align-items: center;
justify-content: center;
}
</style>
<div>
<h1 class="center">title</h1>
<h4 class="center">body</h4>
<div class="center">
<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" height="400px" width="400px" >
</div>
</div>
</body>
</html>
{{--
but the problem with this method that you need to give each element the center class
and in the case of some elments such as an image you need to wrap it inside a div
and pass the center class to it
--}}
{{-- the other way is using css grid --}}
<style>
.center {
display: grid;
place-items: center;
}
</style>
<div class="center">
<h1 >title</h1>
<h4>body</h4>
<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" height="400px" width="400px" >
</div>
{{--
the cool thing about this method that you just need to pass the center class,
in the parent div and evreything inside this div will be centered
and for example you dont need to put the image elemnt in a div in order for it to work
--}}