I have a problem with getting text to appear in the middle of the screen (height-wise) on a webpage. The HTML of the site is:
<html lang="en">
<head>
<title>example</title>
<link href="example.css" rel="stylesheet">
</head>
<body>
<div class="home-container">
<div class="home-row">
<div class="some-other-class">
<p>text that should be in the middle</p>
</div>
</div>
</div>
</body>
</html>
What I want to do is have the home-container element stretch all the way to the bottom of the page, and have the text that should be in the middle in the middle of it. My css looks like:
html, body{
height:100%;
}
.home-container{
width: 100%;
height: 100%;
background-color: rgba(139,0,0,0.4);
}
.home-row{
vertical-align: middle;
}
I understand that what I want to do is possible if I instead make home-container like so:
.home-container{
width: 100%;
height: 100%;
background-color: rgba(139,0,0,0.4);
align-items: center;
display: flex;
}
but this doesn't work on all browsers. What am I doing wrong with the vertical-align property? Id isn't really doing anything in my example...
to use vertical-align:middle add display:table-cellon .home-row and display:table on .home-container
see here jsfiddle or snippet
html,
body {
height: 100%;
}
.home-row {
vertical-align: middle;
display: table-cell;
}
.home-container {
width: 100%;
height: 100%;
background-color: rgba(139, 0, 0, 0.4);
display: table;
}
<div class="home-container">
<div class="home-row">
<div class="some-other-class">
<p>text that should be in the middle</p>
</div>
</div>
</div>
The vertical-align CSS property specifies the vertical alignment of an inline or table-cell box.
read more here vertical align
EDIT 2020
There's a better way to achieve the same result using flexbox
Check snippet below
Play around with flexbox. You can add it on other items not just the container
.home-container {
background: red;
display:flex;
flex-direction: column;
justify-content: center;
height:100vh;
}
<div class="home-container">
<div class="home-row">
<div class="some-other-class">
<p>text that should be in the middle</p>
</div>
</div>
</div>
Try this:
<style>
.home-container {
width: 100%;
height: 800px;
background-color: rgba(139, 0, 0, 0.4);
text-align: center;
}
.some-other-class {
position: relative;
top: 50%;
transform: translateY(-50%);
}
</style>
HTML
<div class="home-container">
<div class="some-other-class">
<p>text that should be in the middle</p>
</div>
</div>
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