I want to center a div vertically with CSS. I don't want tables or JavaScript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.
-
Maybe this? - https://stackoverflow.com/questions/8056554/center-horizontally-and-vertically-of-page-ie-6 – s.kuznetsov May 08 '22 at 17:24
1 Answers
You can do it in multiple ways. I'll start with grid because I love grid.
CSS Grid Layout excels at dividing a page into major regions or defining the relationship in terms of size, position, and layer, between parts of a control built from HTML primitives.
Grid layout enables an author to align elements into columns and rows.
If you want all the elements contained in an element to be vertically centered you can use on the parent element the property display: grid;
and after the property align-items: center;
. For example see this code:
section {
height: 90vh;
width: 100%;
background-color: blue;
display: grid;
align-items: center;
}
div {
height: 100px;
width: 100px;
background-color: brown;
}
<section>
<div></div>
</section>
if you want a specific alignment for each element, you can avoid specifying the property align-items: center;
for the parent element and use the property align-self: center;
directly on each element it contains. See this example:
section {
height: 90vh;
width: 100%;
background-color: blue;
display: grid;
}
div {
height: 100px;
width: 100px;
background-color: brown;
align-self: center;
}
<section>
<div></div>
</section>
another way is through the use of flexbox. The principle is more or less the same. you can apply a rule that applies to all contained elements:
section {
height: 90vh;
width: 100%;
background-color: blue;
display: flex;
align-items: center;
}
div {
height: 100px;
width: 100px;
background-color: brown;
}
<section>
<div></div>
</section>
or specify the position of each:
section {
height: 90vh;
width: 100%;
background-color: blue;
display: flex;
}
div {
height: 100px;
width: 100px;
background-color: brown;
align-self: center;
}
<section>
<div></div>
</section>
If you want to learn more about these topics I leave you the link of the site from which I learned them: https://developer.mozilla.org/en-US/docs/Learn
I hope I have been helpful!

- 61
- 6