Unknown Unknown - 3 months ago 9
CSS Question

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:
width > min-width

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:
width < min-width
Is there a way to fix this problem?

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

Answer

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: 100 auto;
}

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