How to make a <div> with display: inline-block center on the browser horizontally?

elepil
elepil used Ask the Experts™
on
Earlier, I needed a <div> that 'hugged' the elements inside it instead of expanding to the width of the browser. I was advised to set the <div>'s display property to inline-block, and that did the trick.

But after doing that, it no longer would center on the browser. Is there a way I can have a <div> hug its child elements and still be center-able inside the browser?

<html>
    <head>
        <style>

            html {
                min-width: 300px;
                height: 100%;
            }

            #testDiv {
                margin: 0 auto;
                display: inline-block; // If you took this out, it will center again
                width: 100px;
                height: 100px;
                background: red;
                border: 1px solid black;
            }

        </style>
    </head>
    <body>
        <div id="testDiv"></div>
    </body>
</html>

Open in new window


Thanks.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Owner (Aidellio)
Most Valuable Expert 2015
Commented:
Wrap your div in <center> tags :)

Author

Commented:
Rob, thanks! You know, I've never heard of <center> before! Is that something new in HTML5?
RobOwner (Aidellio)
Most Valuable Expert 2015

Commented:
No, it's been around since the beginning of time I believe, just under utilised :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial