say I have HTML as
<div class="page">
<div class="header"></div>
<div class="content">
<div class="foo">
<div>I want to be center of content</div>
</div>
</div>
<div class="footer"></div>
</div>
css
html, body {
height: 100%;
}
body {
margin: 0;
}
.page {
height: 100%;
display: flex;
flex-direction: column;
}
.header {
flex-shrink: 0;
background-color: green;
height: 50px;
}
.content {
flex-grow: 1;
}
.footer {
flex-shrink: 0;
background-color: steelblue;
height: 150px;
}
.foo {
display: flex;
justify-content: center;
align-items: center;
}
https://codepen.io/rrag/pen/PRmOYe
I achieved a sticky footer at the bottom of the page
using flex-grow but that leads to a content with unknown height
How do I center something in the middle of content?
Is it possible using flexbox or may be an alternative approach?
You have almost the exact right idea! Instead of setting your vertical centering rules on .foo (display: flex;, justify-content: center; and align-items: center;), you instead simply need to set them on the parent .content.
This can be seen in the following (Click Run snippet and thenFull page to see this in effect):
html,
body {
height: 100%;
}
body {
margin: 0;
}
.page {
height: 100%;
display: flex;
flex-direction: column;
}
.header {
flex-shrink: 0;
background-color: green;
height: 50px;
}
.content {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
}
.footer {
flex-shrink: 0;
background-color: steelblue;
height: 150px;
}
<div class="page">
<div class="header"></div>
<div class="content">
<div class="foo">
<div>I want to be center of content</div>
</div>
</div>
<div class="footer"></div>
</div>
This can also be seen on CodePen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With