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

Writing Tools That Help Content Marketers Produce Cleaner Work

Content marketing has a hidden tax. It's not the writing itself, it's everything that happens…

2 weeks ago

How Data Analytics Is Actually Driving Smarter Marketing Decisions

Most marketing teams aren't failing because they lack data. They're failing because they can't act…

4 weeks ago

The Ultimate SPF Tester Guide: Boost Email Deliverability In Minutes

Email marketing continues to be one of the most effective ways for businesses to communicate,…

4 weeks ago

Sales Ops: A role that helps sales teams work as efficiently as possible

Xerox first introduced it around the mid-1970s. The need came up because the management activities…

1 month ago

Forex Investment Tips for Beginners

Investing in the forex market may look to be a dangerous game. With some worthwhile…

1 month ago

How Did The Restaurant Industry change In Post Pandemic Era?

The coronavirus outbreak has drastically changed the way we live our lives. Yes, that's absolutely…

2 months ago