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 • Edited on

1 1

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!

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay