Centering Things in CSS

By Hemanta Sundaray on 2021-10-23

The result of the following two code snippets

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="box-container">
        <div class="box"></div>
    </div>
</body>
</html>
style.css
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
  font-family: sans-serif;
}

.box-container {
  width: 30rem;
  height: 30rem;
  border: 0.2rem solid black;
}

.box {
  width: 10rem;
  height: 10rem;
  padding: 0 2rem;
  border: 0.2rem solid red;
}

is the following:

Two Boxes

Technique-1

style.css
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
  font-family: sans-serif;
}

.box-container {
  width: 30rem;
  height: 30rem;
  border: 0.2rem solid black;
  position: relative;
}

.box {
  width: 10rem;
  height: 10rem;
  padding: 0 2rem;
  border: 0.2rem solid red;
}

.box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Technique-2

style.css
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
  font-family: sans-serif;
}

.box-container {
  width: 30rem;
  height: 30rem;
  border: 0.2rem solid black;
  display: grid;
  place-items: center;
}

.box {
  width: 10rem;
  height: 10rem;
  padding: 0 2rem;
  border: 0.2rem solid red;
}

Both the techniques above result in the following:

Centered Red Box

Join the Newsletter