Yo devs ! 🔥
A quick guide on "How to center things in CSS" 🙌
Most of the time, you write great CSS code from colors to complex animations.
But I know most of us (beginners) still struggle to center elements on a viewport perfectly.
Don't worry devs, you are no longer be an noob at the end of this short guide.
Let's get started
There are two ways to center any HTML element on a web page :
1. Using Flexbox
2. Using Transform
- Using Flexbox
HTML code as shown below 👇
<body>
<div class="container">
<div id="object"></div>
</div>
</body>
Now the CSS code
html,
body,
.container {
height: 100%;
overflow: hidden;
}
.container {
display: flex;
justify-content: center;
}
#object {
height: 100px;
width: 100px;
background: red;
align-self: center;
}
- Using Transform
HTML code shown below 👇
<body>
<div class="element"></div>
</body>
Now the CSS code
.element
{
width: 100px;
height: 100px;
background: coral;
}
.element
{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% , -50%);
}
Check out my other posts too 🥂
Author: Jayesh 🧡
You could also use the old style:
#content {
margin: 0 auto;
}
but this works only on block elements, so just add
display: block;
for inline elements.Thanks for sharing!