Quick CSS: How to center an element exactly in the center of the screen

May 13, 2020 Amrish Kushwaha...
twitterlinkedinreddit
Quick CSS: How to center an element exactly in the center of the screen

You want to make a element to be centered aligned in the screen. What are the ways of centering the element in exactly the center in the screen?

Simple!!

Use 4 properties and make any element centered aligned in the your device screen.

	display: flex;
	justify-content: center;
	align-items: center
	min-height: 100vh;

HTML and CSS skeleton

CSS

.wrapper {
	display: flex;
	justify-content: center;
	align-items: center
	min-height: 100vh;
}

Let's see the HTML code for it =>

<div class="wrapper">
	<Any-Element>
</div>

So place any element or div in place of Any-Element and that element or div will be centered aligned of your device screen.

Example: let's make a div centered aligned in the screen

HTML

<div class="object-wrapper">
  <!-- Place any object -->
  <div class="object-div">
    <div class="object">
      <h2>Hi, I am centered aligned!</h2>
    </div>
  </div>
</div>

It's related CSS:

.object-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.object-div {
  max-width: 420px;
  width: 100%;
}

.object {
  background-color: aqua;
  padding: 20px;
  display: inline-block;
  width: 100%;
  text-align: center;
}

And the result is:

https://codepen.io/isamrish/pen/BaoPomd

That's all

I hope that you like the article.

Keep coding and keep learning...