Center Elements in their container - Kodhus

Center Elements in their container

Introduction

In this recipe we are going to take a look at some of the most common ways of centering elements in their container horizontally and vertically.
It is important to know that when we talk about centering an element, it’s about centering it in it’s container. With that said, It’s important that you take into account the position and the size (width and height) of the parent of the element we are trying to position at the center.

Center element horizontally

It really depends on what you are trying to center. If you are trying to center a text within it’s parent, It’s as easy as setting following css property text-align: center on the parent.
Example:

If it is an element other than text, let’s say it is a div or a span or a button, you can use following 2 ways.

Solution 1

Set the position of the element to relative and define the margin as follow:

.element-class {
  position: relative;
  margin: 0 auto;
}

This way the element will be centered relative to it’s parent. As you can see we defined margin 0 and auto. 0 part means that the margin from top and bottom is 0 and the auto part means that the margin from left and right should be automatically calculated which set’s the element to be in the center.
Example:

Solution 2

Set the element’s parent’s position to relative, set the element’s position to absolute and then use transform and left css properties to center the position in it’s parent.

.parent-element-class {
  position: relative;
}
.element-class {
  position: absolute;
  left: 50%;
  transform: translateX(-50%); /* -50% is -50% of the elements width which browser calculates for us */
}

Example:

Share if you liked it: Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

Share
Tweet
+1
Share