DEV Community

Cover image for Aligning elements in CSS 🎯
MilesWK
MilesWK

Posted on

Aligning elements in CSS 🎯

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>
Enter fullscreen mode Exit fullscreen mode

Without any CSS, we get this output:
A very bleak and boring rendering

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;
}
Enter fullscreen mode Exit fullscreen mode

Some better styling
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;
}
Enter fullscreen mode Exit fullscreen mode

Just some code.

Interesting. It moved the text to the halfway down. Let's add another line with that:

.outer-div {
  display: flex;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

A picture. IDK what to put here.
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;
}
Enter fullscreen mode Exit fullscreen mode

It's ugly. It's good you can't see it.
Blech. What is thaβ€”... oh. Let's remove the height and width properties in the CSS:
It's better. Not great.
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>
Enter fullscreen mode Exit fullscreen mode

Just by adding this, we have some interesting results:
Another image. Create the code to see the output!

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)