I have an absolute positioned div centered on the screen and I'd like to prevent it from going off screen. I've seen similar question here on SO, but in my case I don't know the size of the div so I align it using translate/transform.
But when the browser window gets smaller than the div height it goes off screen.
I hoped that adding "max-height: 100vh" will solve the problem, but it doesn't.
Is it possible to keep the whole div on the screen somehow, preferably with CSS?
<!DOCTYPE html>
<head>
<style>
.dialog {
min-width: 200px;
min-height: 150px;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
/* Should not be set! */
/* width: 100px; */
/* height: 100px; */
max-height: 100vh;
overflow-y: auto;
background-color: #aaa;
z-index: 1;
}
</style>
</head>
<body>
<div >
First <br />a<br />a<br />a<br />a<br />a<br />a<br />a<br />a<br />a<br />last
</div>
</body>
CodePudding user response:
You could set a media query to the same min-height
of your dialog and change the min-height
.
.dialog {
min-width: 200px;
min-height: 150px;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
max-height: 100vh;
overflow-y: auto;
background-color: #aaa;
z-index: 1;
}
@media screen and (max-height: 150px) {
.dialog {
min-height: 100vh;
}
}
<body>
<div >
First <br />a<br />a<br />a<br />a<br />a<br />a<br />a<br />a<br />a<br />last
</div>
</body>