Horizontally Center a Smaller Div within a Larger Div

There are times when you have a div container within a div container and need to centralize the inner div container along the horizontal axis. You may have tried align=”center” but this is obsolete. The effect can be simply achieved by applying CSS to the inner div container that needs to be horizontally centralized. This will ensure that the content within the inner container sits neatly within the designated area defined by the outer container.

CSS Option 1

The following CSS code horizontally center the inner div container. Remember that the width of the inner div container, if the width is being defined, needs to be smaller than the outer div container. The margin attribute does the actual horizontal centering. For Internet Explorer 8 and later versions you may want to try this CSS code instead: It centers horizontally without requiring the width to be defined. Remember that the !DOCTYPE tag will be needed in the HTML page for the CSS to work properly on IE8+.

CSS Option 2

Although option 1 is preferred, there is another method. However, it may not work with all browsers. Assuming that the div container is 300px wide, the following code can be used: It is not suitable for very wide containers.

CSS Option 3

If you want to center the inner div container both horizontally and vertically, then the following code can be useful: It is important to consider the pros and cons of each option and remember that more internet users are now accessing the internet through mobile devices like tablets and smartphones. You want to ensure that the CSS code will cater for different screen sizes.

Leave a Comment