DEV Community

Cover image for Day 34 of #100DaysOfCode: Review CSS-Three ways to center the HTML element
Jen-Hsuan Hsieh
Jen-Hsuan Hsieh

Posted on

Day 34 of #100DaysOfCode: Review CSS-Three ways to center the HTML element

Introduction

The Review CSS series is the note for some common CSS usages. Three are three ways for centering the HTML element.

Method 1. Use relative/absolute, top/left, and margin

  1. Use absolute and top/left to center the child component
  2. Move back the child component with margin

Demo

Code

<div class="outer">
  <div class="inner">
    <p>center</p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode
.outer {
  background-color:green;
  position: relative;   
  height: 400px;
}
.inner {
  background-color: blue;
  position: absolute;   
  height: 100px;
  width: 200px;
  margin: -50px 0 0 -100px;  
  top: 50%;
  left: 50%;
}
Enter fullscreen mode Exit fullscreen mode

Method 2. Use relative/absolute, top/left, and translate

  1. Use absolute and top/left to center the child component
  2. Move back the child component with translate

Demo

Code

.outer {
  background-color:green;
  position: relative;   
  height: 400px;
}
.inner {
  background-color: blue;
  position: absolute;   
  height: 100px;
  transform:translate(-50%,-50%); 
  top: 50%;
  left: 50%;
}
Enter fullscreen mode Exit fullscreen mode

Method 3. [flexbox] use align-items and justify-content

Demo

Code

.vertical-container {
  height: 300px;
  display: -webkit-flex;
  display:         flex;
  -webkit-align-items: center;
          align-items: center;
  -webkit-justify-content: center;
          justify-content: center;
  background-color:green;
}

.center{
  background-color: blue;
}
Enter fullscreen mode Exit fullscreen mode

That's it!

Articles

There are some of my articles. Feel free to check if you like!

Top comments (0)