by tephra · 5y ago · 0 comments
.centered { display: flex; justify-content: center; align-items: center; }
Indeed there are two (at least) more ways to both horizontally and vertically center something (using CSS Grid and the good old translate(-50%, -50%)) and with flex I always have a hard time remembering if it is justify-items or justify-content..
<style>
.foo {
display: table;
margin-left: auto;
margin-right: auto; }
</style>
<div class=foo>
<h1>Hello, world!</h1>
</div>
Here, it is only centered when “display: table” is present. e.g. this is not centered: <style>
.foo {
/* display: table; DISABLED */
margin-left: auto;
margin-right: auto; }
</style>
<div class=foo>
<h1>Hello, world!</h1>
</div>
Simple “display: table” two-column layout: <style>
.all {
display: table;
margin-left: auto;
margin-right: auto;
}
.sub {
display: table-row;
}
.left {
display: table-cell;
}
.right {
display: table-cell;
}
</style>
<div class=all>
<div class=sub>
<div class=left>
<h1>Hello, world!</h1>
Left side.
</div>
<div class=right>
<h1>Right bar</h1>
Right side.
</div>
</div>
</div>
There are ways to vertically center content, but since that wasn’t something CSS was designed to do (for the kinds of things where something vertically centered makes sense, we were supposed to be making web apps in Java), they are all clunky.