I am trying to center an element within a parent container. It seems simple with methods like transform, flexbox, and grid... The issue arises with overflow behavior. When the parent container shrinks below the dimensions of the child element, scrollbars appear. However, they do not allow me to scroll to the top-left corner of the child. Here is a visual demonstration: Link to gif animation demonstrating window resizing and CSS behavior
The example code utilizes flexbox for centering, the HTML snippet is provided below:
b {
color: white;
}
html {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
body {
margin: 0;
}
header {
position: absolute;
top: 0;
height: 84px;
width: 100%;
background-color: darkolivegreen;
}
footer {
position: absolute;
bottom: 0;
height: 56px;
width: 100%;
background-color: darkslateblue;
}
main {
position: absolute;
top: 84px;
bottom: 56px;
width: 100%;
background-color: #222222;
display: flex;
justify-content: center;
align-items: center;
overflow: auto;
}
div.content {
flex-shrink: 0;
width: 600px;
height: 600px;
background-color: darkred;
}
<!DOCTYPE html>
<html lang="en">
<!-- head section omitted -->
<body>
<header>
</header>
<main>
<div class="content">
<b>Lorem</b> Lots of Lorem ipsum... <b>quod</b>
</div>
</main>
<footer>
</footer>
</body>
</html>
My desired outcome resembles something like this: Link to gif animation illustrating window resizing and CSS behavior
In this alternative approach, I avoided using flexbox for centering. Instead, I encapsulated the content in a container with auto margins. This achieves horizontal alignment but not vertical. How can I achieve both axes alignment?
Here is the HTML and CSS from the second example implementing a container with auto-margin for centering:
b {
color: white;
}
html {
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
body {
margin: 0;
}
header {
position: absolute;
top: 0;
height: 84px;
width: 100%;
background-color: darkolivegreen;
}
footer {
position: absolute;
bottom: 0;
height: 56px;
width: 100%;
background-color: darkslateblue;
}
main {
position: absolute;
top: 84px;
bottom: 56px;
width: 100%;
background-color: #222222;
/* display: flex;
justify-content: center;
align-items: center; */
overflow: auto;
}
div.container {
margin: 0 auto;
width: 600px;
height: 100%;
background-color: #333333;
}
div.content {
/* flex-shrink: 0; */
width: 600px;
height: 600px;
background-color: darkred;
}
<!DOCTYPE html>
<html lang="en">
<!-- head section omitted -->
<body>
<header>
</header>
<main>
<div class="container">
<div class="content">
<b>Lorem</b> Lots of Lorem ipsum... <b>quod</b>
</div>
</div>
</main>
<footer>
</footer>
</body>
</html>
I hope to discover a solution that does not require JavaScript. If I find one, I will share it along with a corresponding gif.