C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » CSS

Center any element horizontally in CSS

In this article, we are going to learn how to center any element horizontally using CSS? Here, we have some examples which are using to arrange elements alignment horizontally.
Submitted by Abhishek Pathak, on October 10, 2017

CSS is cool. Designing with CSS feels like you are provided with right set of tools to showcase your creativity. New designers often find themselves stuck when something not goes according to them.

One such problem is with the elements that they don't align at the horizontal center of the parent element. Centring element is quite straightforward, once you determine what type of element you want to center.

Centring Inline elements

Inline elements are the elements that go with the content flow. Whereas, block level element takes up new line and space up to the width of the parent element.

Consider this example,

<p>Hi this is a <a href="google.com">Hyperlink</a> example</p>

Now, to center these type of just apply the text-align:center property and it works. Simple, right?

Centring block level elements

The reason why these elements are not centred because they won't follow the rule of text-align: center. They are block level elements. They take up new line and space equal to width of the parent element.

To center the block element, we have to define a size and then apply margin property.

Code:

.block-element {
	width: 200px;
	margin: auto;
}

First, we will discuss about the margin: auto property, which sets the margin to auto. This property set the margins from both left and right to auto. This means that from both left and right the margins will be equal, which is how an element centers.

But, it won't work directly. As you know, the block element takes up 100% width, the element as a whole is centred for CSS. So we need to reduce the width in order to work. Now since the width is less than the parent container's width, the margin property will equalize the left and right margins, and that is how you get block element at center.

Here is a demo,

DEMO

Output

Center alignment using CSS

HTML code with the CSS

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSS center elements example</title>
  
  <!-- CSS code below -->
  <style>
  
    .inline {
      text-align: center;
    }
    
    .box {
      width: 200px;
      height: 100px;
      background: #ddd;
      margin: auto;
    }
  
  </style>
  
</head>
<body>
 
 <h2>CSS Centering elements example</h2>
 <h3>1. Inline element</h3>
 <p class="inline">Just apply the text-align:center to make it in center like this</p>
 
 <h3>2. Block Element</h3>
 <div class="box">
   <p class="inline">The block element with custom width and auto margin at the center of the page</p>
 </div>
  
</body>
</html>

Hope you like the article. For more awesome articles stay tuned.









COMMENTS