简体   繁体   中英

div doesn't center when browser is smaller than min-width

I am trying to center a div. The div has a width of 400pt, the body has a width of at least 500pt, to leave a space of min. 50pt around the div. My code looks like this:

<html>
    <style>
        body{
            min-width:500pt;    
        }

        #centered{
            position:absolute;
            background-color:#ff0000;
            width:400pt;
            left:calc(50% - 200pt);
            height:400pt;
        }
    </style>
    <body>
        <div id="centered"></div>
    </body>
</html>

As long as the width of the browser is greater than min-width , everything works fine: 宽度>最小宽度

But as soon as the width of the Browser gets smaller than min-width , and a scrollbar appears at the bottom, the div is only centered in the space you see, when the scrollbar is on the left, but not centered in the middle of the whole (scrollable) body: 宽度<最小宽度 Is there a way to fix this problem?

If you don't understand my problem, feel free to ask.

There is no need to have a min-width for your body, just add this

#centered{   
max-width: 400px;
   width: 100%;
   position: relative;
   background-color: red;
   display: block;
   margin: 100px auto;
}

If it doesn't work for you feel free to comment :)

Try this one

<style>
    #centered{
        position:absolute;
        background-color:#ff0000;
        width:400pt;
        left:calc(50% - 200pt);
        height:400pt;
    }
    @media screen and (max-width: 500pt){
        #centered{
            width:100%;
            left:0px;
        }
    }
</style>

<body>
    <div id="centered">
    </div>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM