How can i horizontally center a div?

If coding is more your thing then the Website Development & Scripting forums are for you. Share server-side scripting and database integration tips, tricks and problems here.
Post Reply
agoston
Newbie
Posts: 3
Joined: Mon Sep 23, 2019 9:03 am

#1

Hello,

How can I horizontally center a <div> within another <div> using CSS?

Code: Select all

<div id="outer">
  <div id="inner">Hello World!</div>
</div>


User avatar
rigsby
Junior Member
Posts: 13
Joined: Fri Sep 29, 2017 8:56 am

#2

You can apply this CSS to the inner <div>:

Code: Select all

#inner {
  width: 50%;
  margin: 0 auto;
}
Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

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

Code: Select all

#inner {
  display: table;
  margin: 0 auto;
}
It will make the inner element center horizontally, and it works without setting a specific width.

Working example here:

Code: Select all

#inner {
  display: table;
  margin: 0 auto;
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%
}

Code: Select all

<div id="outer">
  <div id="inner">Hello World!</div>
</div>
Post Reply
  • Information
  • Who is online

    Users browsing this forum: No registered users and 0 guests