DO YOU NEED A CONTENT WRITER FOR YOUR BUSINESS?

Your One-Stop Solution for All Content Needs! Click here for more!
Categories: Css

Horizontally center a div within a div using CSS style

Share

Sometimes we need to horizontally center a div that is within another div using CSS that make the inner element center horizontally.

In that case, you don’t have to set the width to 50%. So, any width which is less than the containing div will work.

Let’s see how to horizontally center a div.

For example, you have the following HTML:

<div id="outerDiv" style="width: 100%">
<div id="innerDiv">Content goes here...</div>
</div>

Apply this CSS to the inner div:

#innerDiv {
width: 50%;
margin: 0 auto;
}

The margin: 0 auto is what does the actual centering.

#outerDiv {
width: 100%;
text-align: center;
}

That makes the inner div centered with text-align.

Read Also: Align text vertically next to an image

If you are targeting IE8+, then you can use this instead:

#innerDiv {
display: table;
margin: 0 auto;
}

This will make the inner element center horizontally without setting a specific width.

Using box model:

#outerDiv{
width:100%;

/* Firefox */display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;

/* Safari and Chrome */display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;

/* W3C */display:box;
box-pack:center;
box-align:center;
}
#innerDiv{
width:50%;
}

If you are targeting IE8+, this might be better to have this instead:

#innerDiv {
display: table;
margin: 0 auto;
}

This will make the inner element center horizontally and this works also without setting a specific width.

CSS Designer

Recent Posts

Flawless Prize Fulfilment and Management That Takes Your Marketing Campaigns to the Next Level

In today’s fast-paced and highly competitive marketing environment, even the most creative campaign is only…

1 day ago

Moving company Zeromax in NYC

We are NYC moving firm. Are you planning a flat move? Maybe a distance or…

5 days ago

Mobile testing: An important task for smooth functioning of the device

Mobile devices, unlike desktops and laptops, can not be handled by dozens or hundreds of…

6 days ago

Augmented Reality in Education is Blowing Up the Candles!

Augmented Reality- An immersive experience for the learners! Learning and education aren’t the same as…

1 week ago

Here Are 4 Diamond Studs for You to Gift Your Special Ones

On special days like birthdays and weddings, we all like to celebrate our loved ones…

1 week ago

7 Best Web Application Development Tools

A web application is different from a regular mobile or desktop application as it runs…

1 week ago