Centering anything in CSS

Somesh
3 min readNov 24, 2021

Have you ever faced with difficulty in centering things while developing a website? As a beginner I faced this issue too often in my hobbie projects and in my internship projects as well. So I’ve found some easy ways to do this with just three lines of CSS properties. Let’s dive deep in.

Image from logolynx.com

Things to be done before starting…

HTML code

From Carbon.now.sh

SCSS code

From carbon.now.sh

Output:

Result

That’s it to be done to follow along. Now, Let’s see how to bring that button to the center of the screen…

From carbon.now.sh

Output:

Result

Decoding the code…

The position property is set to absolute which takes the button out of the normal HTML elements flow. Since no parent element’s position is set to relative the element is positioned relative to the body of HTML.

Now, the magic is done by the last three lines, which makes the button to be centered. This could be extended to any other similar use cases.

Codepen For Your Reference

Codepen

Now, let’s see a different case where you need to handle centering…

Centering paragraphs inside a div tag

First creating a div element and adding some CSS to it.

HTML Code
SCSS Code

Output for now

Result

Now let’s apply the previous knowledge and new concept to center the wrapper div in the whole page and the <p> tag inside the wrapper div.

Chaged wrapper div

Finally arrived at…

Result

Codepen for your reference

Conclusion

These are the two easy methods which I’ve found useful. If you know any other method which is more easy than this, mention in the comment section.

I am planning to learn React. I thought of making a series about React while learning. Is there anyone to learn with me??? If so follow me for more updates!!!

That’s all for today, see you guys in the next article…

--

--

Somesh

Software Developer | Loves writing about technology.