Okay! So you got stuck in horizontally aligning <div> element to center. Its fine. Trust me, I’ve been there. It even gets more frustrating when you stumble across several solutions for a problem simple as this. Mind you, I said simple, coz let’s face it how hard can it be to just center a div block with just primitive lines of code. But as you go on coding, somewhere you come across a situation where it just doesn’t work with more CSS for more elements. As your code complexity increases, you have to be adept at knowing the perfect solution suitable for your cause. With that consideration, Here I’ve managed to compile some solutions to horizontally align div block with text or some catchy graphics in center and in the middle of horizontal screen using simple HTML and CSS.

Just to be clear, We will be focusing to align elements not on the center of the screen (though there will be some examples mentioned) but just central to its horizontal line. We will be discussing some of the usage and problems of using particular solutions.

Horizontally Align Center a div block using HTML and CSS

Okay folks! lets get started. Just for fun, I’ve setup a background to the body. It’s not important, but hey, I am trying to make it look as cool as possible.

body{
   font-family: 'Dancing Script', cursive;
   background-color:#0A4A8A;
}

1. Center Text alignment with text-align

Well it’s the basics. We are simply assigning the value of text-align property of the given block to center so that we can horizontally align the text within the div block or in this case h1 tag to center. Okay, lets see the HTML to align the div to center.

HTML

<h1>Horizontal Centering Tutorial (Text-align Method)<h1>

Okay! You caught me! We said alignment of div block and we aren’t using any div. But I just want this first part to be catchy so I added the h1 tag. If you want to get stringent, feel free to add div in place of h1 with a class name, if you please.

CSS

h1{
  text-align:center;
  color:white;
}

Simple? Well here is a tricky part. The alignment is relative to its parent block. For now the parent of the above text is the body element. So, the text is aligned horizontally center of the body element. You lost me here, right? The next section might help.

2. Center Text-alignment with respect to parent

Okay add the following html

 <div class="text">
    <h2>HTML and  CSS (Text-align on block Method)<h2>
  </div>

Now the CSS to align the div element from HTML to center:

.text{
  text-align:center;
  background:green;
  color:white;
}

I’ve set the background color to locate the coverage of our div block.

Tex-align method to align div block middle of horizontal screen
text-align on div block

Same Old, Same Old! right?? Okay that’s not what I wanted to teach you. Now set the width property of the text class

width:400px;
text-align on div block
text-align center with width set

Ooh!! getting interesting right?? It seems that the text that you thought you aligned horizontally to center has moved from the center position, though still the CSS value of text-align is center. It’s because the text is aligned to center with respect to its parent block. If you observe carefully, you can see the text are still in center with respect to its parent block which now covers just 400px of the screen as evident by the black background.

Now Can you align the entire black background block to the center? Let’s do that in next section

3. Center Alignment With Margin auto

Let’s add the following CSS code to CSS of our text class that will align the div block horizontally center to the screen.

margin: 0 auto;

The above code is just a shorthanded CSS that implies zero margin to top and bottom while the right and the left margin are set to auto. Now you can clearly see the green background has been centered horizontally. So, With that simple CSS we can align the block at the middle of the horizontal screen.

Note: The value of width needs to be set for this trick to work.

text-align on div with margin
text-align:center, width:400px, margin:0 auto

Did I mention that we can actually align block to center with just margin property? No not with auto value, that’s an implicit alignment. You could explicitly set margin-left value by experimenting with some values, if you want. But why hassle when you have implicit value, right? I am just saying that there is an option. Try it, if you want. I would set the value to 50% subtracted by the half of the percentage covered by the element to be centered.

4. Flex-box to align block horizontally center

Okay! Lets check out the flex-box layout. Flex box layout provides effective one-dimensional model to align the elements. It provides a powerful capabilities to arrange the elements on one dimensional pane. I recommend learning flex-box layout especially for responsive designs.

Now using flex-box design lets align a block at the middle of horizontal screen. Okay, lets add the following HTML

<div class="flexbox_1">
    <img src="https://onaircode.com/wp-content/uploads/2017/11/logo-new-color-1.png">
  </div>

Okay I have a parent element with class flexbox_1 and a img child. You can use text instead. Now lets add the CSS to align the image horizontally center to the screen.

.flexbox_1{
  display:flex;
  justify-content:center;
}

The code is simple. The display property sets the flex-box layout of the parent element. and the justify-content horizontally aligns the child to center.

For this method, we don’t need additional margin property to be set.

flex-box to align for single block at the middle of horizontal screen
display:flex; justify-content: center

Now lets see when flex-box is more suitable to be applied. Coz, let’s face it when you have simple code like margin: 0 auto why do we want to bother with this flex-box, right? Okay first of all lets see an example using the margin property to center align multiple div block within another div block. on another section.

5. Center Alignment of Multiple div Within a div Using Margin Property

First of all, Lets create a div within a div using following HTML which will be aligned to center horizontally with CSS.

<div class="multiple_margin">
    <div class="red">Child 1</div>
    <div class="yellow">Child 2</div>
  </div>

Then just like we did for number 3. Lets repeat the CSS.

.multiple_margin{
  width:400px;
  margin:0 auto;
}

And just to distinguish each child element, I am adding colors to each child with the following CSS.

.red{
   background:red;
}
.yellow{
  background:yellow;

}

Hmm!! Now lets see the output.

center using css Margin Property
multiple child with margin

Now That seems fine, right? But did you consider, what if you wanted your child element to be horizontally adjacent to each other. In that case, flex-box is the layout model for you. So, in next section we will be seeing the the usage of flex-box

6. Flex-box to align multiple div horizontally center and adjacent to each other

The HTML we will be using is similar to that of number 5.

<div class="flexbox_2">
     <div class="white">Child 1</div>
    <div class="pink">Child 2</div>
  </div>

Lets add CSS for just like we did in number 4 to align the div elements of above HTML to center.

.flexbox_2{
  display:flex;
  justify-content:center;
}

And Also, for extra lookup. Lets add following CSS to our child element.

.white{
  width:200px;
  height:200px;
   background:white;
   font-size: 2em;
   text-align:center;
}
.pink{
  width:200px;
  height:200px;
  background:pink;
  font-size:2em;
  text-align:center;
}

Okay, I’ve added text-align: center to align the text to middle of the horizontal plane. I hope you got that. So, lets see the output and compare it to the output of number 5.

flex-box to align div block to at the middle of horizontal screen
Flex-box for Multiple block

Just to be clear, there is a flex-direction property on flex-box layout model which by default is set to row. That’s why the child elements appear horizontally adjacent. If you set the property to column, the child elements would appear vertically adjacent.

7. Absolute Positioning Method

Well, as of now we just discussed two different important methods only if you are a good observant. (text-align doesn’t count as it aligns text). So, lets explore some more options.

In this method we will position our element to absolute which obviously gives freedom to arrange it wherever we prefer. But it comes with a downside. Absolute positioning doesn’t care about other elements and it just stacks on top of other elements if it’s position is occupied. Rude! But hey, if you want to use absolute positioning, who am I to judge. Just saying, it needs to be handled correctly.

Let’s add the HTML

 <div class="absolute_positioning">
    Absolute Positioning
  </div>

Now Here, I will be aligning the element center to the screen not just horizontally but vertically also.

.absolute_positioning{
  position:absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  /* for extra designs */
  background-color:black;
  color:white;
  width: 200px;
  height: 50px;
  font-size:1.5em;
  
}

Well yea, the element is first set to 50% from the left and 50% from the right. That puts the element to center. Now If our element was a simple point or a dot, then we got nothing left to do. But since the element possess it’s own width and height, we are just translating 50% of the elements width to both dimension (top and right) effectively centering the element to the screen. This gives the advantage to adjust the element without having to know it’s dimension. So, lets see our outcome

Absolute positioning of div to align center horizontally
Absolute positioning to center

Oh oh! See, told you, the absolute positioning just stacks over the another element. But lets correct our values. It’s all about experimentation. Okay, lets see what I’ve got.

.absolute_positioning{
  position:absolute;
  left: 50%;
  top: 80%;
  transform: translate(-50%, -5%);

  /* for extra designs */
  background-color:black;
  color:white;
  width: 200px;
  height: 50px;
  font-size:1.5em;
  
}

I played with the value of top propery and transform property and I got the desired output:

Absolute positioning CSS to align the div horizonally center

8. Grid layout to align div center horizontally

If you are familiar with Grid layout, then probably you know using grid for center alignment is just pathetic attempt to accomplish a simple thing with a complex concept. But sometimes, when you are opting for grid based layout on your whole document, you might want to try this approach.

Grid is two dimensional layout model contrasting flex-box method. Both are explicitly used for aligning elements. Grid is essentially used when you want to align elements considering both dimensions. For now, we will be implementing it for horizontal center alignment only. Let’s see how it’s done.

 <div class="grid">
    <h2>Center Alignment with Grid</h2>
  </div>

Now lets add some CSS with grid layout aligning the text to center horizontally.

.grid {
  display: grid;
   justify-items: center;

/* just for extra design */
   margin-top:2px;   
}

Well the code is simple as that. Not so complex after all, huh!! Okay, Just to show off. Lets add designs to our child text so that the child elements could be easily distnguished at the middle of the horizontal screen with its div block align to center.

.grid h2{
 background:#f0e68c;
 padding:4px;
 color:black;
}
Grid based horizontal center alignment
Grid method for horizontal Center alignment

9. JavaScript Align div center horizontally

This may contradict the topic to align using CSS but to be fair, we will be using Javascript just to manipulate the CSS property of elements. Sometimes there comes a situation when you want your users to explicitly manipulate the DOM of your webpage, or your application may require the dynamic alignment of elements. In that case, CSS alone wont be of much help. So lets learn how can we use Javascript to change the CSS element so that we can align div element center horizontally in dynamic usage.

First of all We need to have HTML element which will trigger the Javascript code which align the selected element to middle of the horizontal plane by changing the CSS of the element.

<div id="dynamic_change">
  <p> Javascript code will change the CSS of this element</p>
</div>

Okay, the above HTML provides a simple div element with a id wherein a text is present which we will align by the use of Javascript to the center horizontally or at the middle of the horizontal line. But for that we need another element to trigger the html. I have created a basic button for the purpose.

<button onClick="align_center()">Click me align center</button>

With above HTML, you should be seeing a basic button appearing at your screen. That does nothing for now. So lets add a javascript to align the above dynamic_change div horizontally center by manipulating its CSS.

Text-align

Now within your script tag add the following JS code which will align the div and the text within to center by manipulating its CSS.

function align_center(){
     document.getElementById('dynamic_change').style.textAlign='center';
  }

With that code running, Now if you click on the button you should see the text within the div block is aligned to center horizontally as the JS successfully manipulated it’s CSS.

Margin

Since with JavaScript, you can manipulate the CSS, you have options to align the above text within dynamic_change dive element to center horizontally by changing the CSS of other properties that we have discussed above. To align the above text to center or middle to horizontal line of the screen we can set the following JS code manipulating the margin CSS of the div.

function align_center(){
    document.getElementById('dynamic_change').style.width = "400px";
     document.getElementById('dynamic_change').style.margin = "0 auto";
  }

As mentioned earlier, margin property works only when width is set so that’s why we’ve set the width property of the div block.

Absolute Positioning

Likewise we can also manipulate the absolute positioning CSS to align the div and the text within to align them to center horizontally. Let’s see its corresponding JS code:

<script type="text/javascript">
  function align_center(){
    document.getElementById('dynamic_change').style.position = "absolute";
     document.getElementById('dynamic_change').style.left = "50%";
      document.getElementById('dynamic_change').style.right = "50%";
       document.getElementById('dynamic_change').style.transform = "translate(-50%,-50%)";
  }

Flexbox

Similarly, We can also manipulate CSS for flex layout model. JS code follows:

function align_center(){
    document.getElementById('dynamic_change').style.display = "flex";
     document.getElementById('dynamic_change').style.justifyContent = "center";     
  }

Grid

Similarly, we can also change align the text to center by using Grid approach in JS.

 function align_center(){
    document.getElementById('dynamic_change').style.display = "grid";
     document.getElementById('dynamic_change').style.justifyItems = "center";
      
  }

Conclusion

Phew! That was a lot. Anyways, the choice of proper solution always depends on the application that you are developing. Each method has its own perks and defects. You have to identify the relevant approach to your solution. Me, I prefer mostly the flex-box approach provided it’s responsiveness and simplicity. Well, I have tried to compile several approaches to center div and text using CSS while the implementation rests solely on you as a developer.

For now, that’s it. Congrats, you held through!