Centering a Div / Fullscreen pages
A common web pattern for formatting websites.
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Full Page Layout</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Header</h1>
</header>
<main>
<section>
<h2>Main Content</h2>
<p>This is the main content area.</p>
</section>
</main>
</body>
</html>
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
header {
text-align: center;
padding: 1em;
color: white;
background-color: #333;
}
main {
display: flex;
justify-content: center;
flex: 1 0 auto;
padding: 1rem;
background-color: rgb(199, 199, 199);
}
section {
width: 800px;
text-align: center;
padding: 1rem;
background-color: rgb(160, 160, 160)
}
@media only screen and (max-width:800px) {
section {
width: 100%;
}
}
Reasons
-
1. Set the body to flex and min-height
body { display: flex; flex-direction: column; min-height: 100vh; }
Setting the body to display:flex makes the body section a "flex container" and its children "flex items". Flex items are given the ability to grow and shrink dynamically, based on the flex container.
Setting the min-height: 100vh. Allows the body to always display at least one full height of the viewport.
-
2. Set the main container to flex: 1 0 auto
main { display: flex; flex-direction:column; align-items: center; flex: 1 0 auto; padding: 1rem; }
Setting flex: 1 0 auto, is short form for flex-grow:1, flex-shrink:0 and flex-basis: auto. In other words the container will grow as much space that is available, never shrink and its initial size is based on its content.
-
3. Set the section fixed desktop width and responsive mobile width.
section { width: 800px; text-align: center; padding: 1rem; } @media only screen and (max-width:800px) { section { width: 100%; } }
Set the widths for the section. This is where the actual content will be.