Read : 1 minutes. 30 November 2022
Tags: Website

how to center element horizontally

Example centering a div element horizontally inside another div using css

Example centering a div element using the id on the div

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

You can apply this CSS to the inner <div>

1#inner { width: 50%; margins: 0 auto; }

of course, you don’t need to set the width to 50%. Any width less than the containing <div> will work. Here’s the margin: 0 auto that does the actual centering.

If you’re targeting Internet Explorer 8 (and later), it might be best to have this instead:

1#inner {
2  display: table;
3  margins: 0 auto;
4}

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

Working example here:

 1#inner {
 2  display: table;
 3  margins: 0 auto;
 4  border: 1px solid black;
 5}
 6
 7#outer {
 8  border: 1px solid red;
 9  width:100%
10}
1<div id="outer">
2  <div id="inner">Foo foo</div>
3</div>

To center a div vertically, use the align-items: center.

how to center element horizontally