May

12

Vertically Align Text or Elements Using CSS

Posted by Leave a Comment

In the past, getting text or other elements to align vertically was often much harder than it should have been. Luckily, modern CSS makes this task much simpler; as simple as three lines actually.

First, we’ll create a container div with a border so we can see the parent element we want to align to:

<div class="container"></div>
.container {
  width: 100px;
  height: 100px;
  border: 1px solid black;
}

Now if we add some text to our container div we only need three lines of CSS to vertically center our text:

<div class="container">
<p>some text</p>
</div>
.container p {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

The same can be applied to other elements as well. Here we’ll add another div of fixed width and height to our container div and apply the same CSS rules:

<div class="container">
<div class="content">
</div>
</div>
.content {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

I also added the ‘left’ and translateX properties to horizontally center the div as well. See both examples in action below:

Category: CSS, Development, Uncategorized, Web Development

Leave a Reply