简体   繁体   中英

How to prevent a vertically-centered div from disappearing off of small screens

I have the following CSS that I use to vertically center a DIV on a page (and horizontally center it as well). If the height of the browser window is less than 600px, I would like the window to be able to scroll to show the entire DIV. However, the DIV just centers itself on the page and anything beyond the height of the browser is hidden--no scroll bars. Is there any way to allow the user to scroll to these now hidden regions?

#container{
    width:800px;
    height:600px;
    position:absolute;
    margin-top:-300px;
    top:50%;
    margin-left:-400px;
    left:50%;
}

Add a @media query for max-width and max-height

@media (max-width: 800px) {
    #container {
        left: 0px;
        margin-left: 0px;
    }
}

@media (max-height: 600px) {
    #container {
        top: 0px;
        margin-top: 0px;
    }
}

JSFiddle

you could also try adding

overflow:scroll;

The overflow property specifies what happens if content overflows an element's box.

check this one

#container{
position: absolute;
top: 50%;
left: 50%;
width: 30em;
height: 18em;
margin-top: -9em;
margin-left: -15em;
border: 1px solid #ccc;
background-color: #f3f3f3;
}

use this

  #container
    {
    width:800px;
    height:600px;
    margin-left:auto;
    margin-right:auto;
    }

You are using position: absolute; so there's no way this can be achieved unless and until you make a div with min-width and margin set to auto

<div>vertically centered div</div>
<div>min-width div</div>

div:nth-of-type(2) {
   min-width: 1000px; /*Change accordingly*/
}

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