Horizontally Center Align
tag in HTML using CSS


A <div> (division) tag is used as a container to divide your HTML page into multiple sections. When you create a new <div> tag without any CSS style being applied, it will not inherit anything from its parent tag, you would see that a line-break is introduced before and after the div element.

By default the div will be left-aligned to the page or the container which holds it, in order to horizontally center align it, you could try one of the following,

  1. Using display:inline-block

  2. Let's have two div tags - we call them the inner div and other div. If you check the below code, it will align the inner div to top right.

     <div class="outerDiv" id="outerDiv" style="width:300px;background-color:#eee">
    <div class="innerDiv" id="innerDiv" style="padding:10px;background:#ccc">
    Inner Div Element text
    </div>
    </div>

    We would require to apply CSS to both divs in order to horizontally center align the inner div. Add width:100% to outer div so it takes up browsers width, also add text-align:center if you want the text it in to be center-aligned as well. To the inner div add display:inline-block.

    <div class="outerDiv" id="outerDiv" style="width:300px;background-color:#eee;width:100%;text-align: center">
    <div class="innerDiv" id="innerDiv" style="padding:10px;background:#ccc;display: inline-block;width:100px">
    Inner Div Element text
    </div>
    </div>
  3. Using margin: 0 auto;

    <div class="outerDiv" id="outerDiv" style="width:100%">
    <div class="innerDiv" id="innerDiv" style="margin: 0 auto;width:50%;background-color:#eee;text-align:center">
    Inner Div Element text that needs to be horizontally aligned to center of the page
    </div>
    </div>

⚠️ Note: One of the older and easiest way to achieve this wrapped the div with a <center> tag, please be aware that center tag is deprecated in HTML5.

Advertisements
Try Out Code2care Dev Tools:

Advertisements



Android Java Linux Microsoft Google Python macOS Notepad++ Microsoft Teams CSS PHP SharePoint Html Linux C Programs Bootstrap jQuery Sublime Android Studio Facebook Eclipse WhatsApp News MySQL Json HowTos JavaScript FTP S3


Advertisements


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Tutorials, Trouble-Shooting steps, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.
🎉 We are celebrating the 10th years of Code2care! Thank you for all your support! We hope we made a difference.
We strong support Gender Equality & Diversity.

We stand in solidarity with Ukraine - Make a donation to UNHCR - https://donate.unhcr.org/in/en-in/ukraine-emergency