Aligning elements in CSS is hard. It is ridiculously hard. If only you could algin a DIV element using this-item: center. (you can't BTW). Let's learn how to properly align items in CSS.
Get your programming hat on, and lets get started! 🤠
1. Setup
Let's take some HTML to start:
<div class="outer-div">
<div class="inner-div">
<h1>Hello, World!</h1>
<p>This is an element</p>
</div>
</div>
Without any CSS, we get this output:

Let's add some CSS to spice things up a little:
.outer-div {
/* Aligning stuff will go here */
}
.inner-div {
width: 150px;
height: 150px;
background-color: blue;
/* Some more aligning stuff will go here */
}
h1,
p {
font-family: sans-serif;
}

This isn't perfect, but it will do.
2. Centering stuff
Let's add one line of CSS to the .outer-div element:
.outer-div {
display: flex;
}
Interesting. It moved the text to the halfway down. Let's add another line with that:
.outer-div {
display: flex;
justify-content: center;
}

Nice! It actually centered the element.
Let's put the same two lines of code with the .inner-div element:
.inner-div {
width: 150px;
height: 150px;
background-color: blue;
display: flex;
justify-content: center;
}

Blech. What is tha—... oh. Let's remove the height and width properties in the CSS:

Okay. That makes it better. Not great.
Let's update the HTML. Here is all of the HTML:
<div class="outer-div">
<div class="inner-div">
<h1>Hello, World!</h1>
<p>This is an element</p>
</div>
<!-- Another one! -->
<div class="inner-div">
<h1>Hello, World!</h1>
<p>This is an element</p>
</div>
</div>
Just by adding this, we have some interesting results:

In the .outer-div CSS code, change the justify-content: center to justify-content: space-between:

This is the basics of styling.
⬇️ Thank you for reading! Have any tips and tricks! Let us now below! ⬇️
Note: There will be a part 2!

Top comments (0)