by Sai gowtham

How to horizontally center elements (div) in Css

In this tutorial, we are going to learn about three different ways to horizontally center the elements in css.

1. Horizontally centering using flexbox

To horizontally center a elements like (div) we need to add display:flex and justify-content:center to the element css class.

Example:

<div class="center">
   <h1>I'm Horizontally center</h1>
</div>
.center{
   display:flex;
   justify-content:center;
}

horizontal-center-using-flex-box

2. Horizontally centering using margins

This example shows you how to horizontally center elements using margins and width.

.center{
    width:50%;
    margin:0 auto;
}

In the above code, we have added width:50% and margin:0 auto so that the element equally splits the available space between the left and right margins.

3. Horizontally centering using transform

This example shows you how to horizontally center elements using position and transform properties.

.center{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
  1. Here first we added position:absolute, so that element comes out from the normal document flow.
  2. second we added left:50%, so that element moves forward 50% towards x-axis.
  3. Third, we added transform:translateX(-50%), so that element comes backward 50% and align it to center.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course