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
- Use absolute and top/left to center the child component
- Move back the child component with margin
Demo
Code
<div class="outer">
<div class="inner">
<p>center</p>
</div>
</div>
.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%;
}
Method 2. Use relative/absolute, top/left, and translate
- Use absolute and top/left to center the child component
- 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%;
}
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;
}
That's it!
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
- My latest side project - Daily Learning: https://daily-learning.herokuapp.com/
Top comments (0)