We can center horizontally a block-level element by using the CSS margin property, but CSS width property of that element should be set.
Let’s see an example to center an element using CSS margin property −
Example
<!DOCTYPE html>
<html>
<head>
<title>Center Alignment using CSS Margin</title>
<style>
#yinyangSymbol {
width: 100px;
height: 50px;
background: #fff;
border-color: #000;
border-style: solid;
border-width: 2px 2px 50px 2px;
border-radius: 100%;
position: relative;
}
#yinyangSymbol::before {
content: "";
position: absolute;
top: 50%;
left: 0;
background: #fff;
border: 18px solid #000;
border-radius: 100%;
width: 14px;
height: 14px;
}
#yinyangSymbol::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
background: #000;
border: 18px solid #fff;
border-radius:100%;
width: 14px;
height: 14px;
}
div{
width: 50%;
margin: 10px auto;
border:4px solid black;
}
#text {
border: 4px solid black;
background-color: grey;
color: white;
text-align: center;
}
</style>
</head>
<body>
<div id="main">
<div>
<div id="yinyangSymbol"></div>
</div>
<div id="text">Be Centered & Balanced</div>
</div>
</body>
</html>Output
This will produce the following output

Let’s see another example to center an element using CSS margin property −
Example
<!DOCTYPE html>
<html>
<head>
<title>Center Alignment using CSS Margin</title>
<style>
.screen{
padding: 10px;
margin: 10px auto;
text-align: center;
color: white;
border-radius: 0 0 50px 50px;
border: 4px solid #000;
}
.screen1 {
background-color: #f06d06;
width: 70%;
}
.screen2 {
background-color: #48C9B0;
width: 50%;
}
.screen3 {
background-color: #DC3545;
width: 30%;
}
</style>
</head>
<body>
<div class="screen screen1">Screen 70%</div>
<div class="screen screen2">Screen 50%</div>
<div class="screen screen3">Screen 30%</div>
</div>
</body>
</html>Output
This will produce the following output
