Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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

<div id="outer">  

  <div id="inner">Foo foo</div>

</div>

1 Answer

0 votes
by (40.7k points)

Try using this CSS code to the inner <div>:

#inner {

  width: 50%;

  margin: 0 auto;

}

Note: It's not needed to set the width to 50%. Since any width less than the containing <div> will work. But you must add the margin: 0 auto because this will help you in actual centering.

But if you are working on IE8+ browser, then the below code will be the right choice for you:

#inner {

  display: table;

  margin: 0 auto;

}

 The above code will make the inner element center horizontally and it'll work without setting a specific width.

For example:

#inner {

  display: table;

  margin: 0 auto;

  border: 1px solid black;

}

#outer {

  border: 1px solid red;

  width:100%

}

<div id="outer">

  <div id="inner">Foo foo

</div>

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...