Computer >> Computer tutorials >  >> Programming >> CSS

How to center an element vertically and horizontally with CSS?


To center an element vertically and horizontally with CSS, the code is as follows −

Example

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .centered {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 200px;
      border: 3px solid rgb(0, 70, 128);
   }
</style>
</head>
<body>
<h1>Centering Example</h1>
<div class="centered">
<h2>This text is centered vertically and horizontally both</h2>
</div>
</body>
</html>

Output

The above code will produce the following output −

How to center an element vertically and horizontally with CSS?