How to Center a DIV Inside Another DIV with HTML and CSS?

In CSS, there is no direct way to float an element to the center.
Instead, we use other techniques to achieve perfect centering. Below are two common methods:
- Using margin: auto to Center a DIV
- Using Flexbox for Modern Centering

Using margin: auto to Center a DIV

This method works when the element has a defined width and is block-level.
Here's an example:

code:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center DIV with Margin Auto</title>
<style>
  .content {
    background-color: yellow;
    padding: 20px;
  }
  .block {
    width: 50%;
    height: 200px;
    background-color: red;
    margin: 0 auto; 
    text-align: center;
    line-height: 200px;
  }
</style>
</head>
<body>
<div class="content">
  <div class="block">
    BLOCK
  </div>
</div>
</body>
</html>


result:


BLOCK








JSFiddle

Using Flexbox for Modern Centering

Flexbox is a powerful layout tool that allows easy centering both horizontally and vertically.
Here's an example:

code:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center DIV with Flexbox</title>
<style>
  .content {
    display: flex;
    justify-content: 
    align-items: center; 
    background-color: yellow;
    height: 100vh; 
  }
  .block {
    width: 50%;
    height: 200px;
    background-color: red;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
</head>
<body>
<div class="content">
  <div class="block">
    BLOCK
  </div>
</div>
</body>
</html>


result:


BLOCK

















Privacy Policy