Vertically and horizontally align div into parent div
Solution 1
There are many ways that this can be achieved but the one I find most useful is to change the div display to a table cell as table cells support vertical alignment.
As an adjustment to your sample code...
HTML
<div class="img">
<div class="text">Here is my slogan</div>
</div>
CSS
.img {
margin: 0px;
padding: 0px;
border-width: 0px;
background-image: url("picture-1.jpg");
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size: 100% auto;
background-color: black;
min-height: 1024px;
display: table;
width: 100%;
}
.text {
text-align: center;
height: 300px;
display: table-cell;
vertical-align: middle;
}
Note the addition of display: table
to the .img
class and the addition of display: table-cell
and vertical-align: middle
to the .text
class.
This has been tested and saved at https://jsfiddle.net/wLm5zjwx/
Solution 2
Try CSS Flexbox: display: flex; align-items: center;
Related videos on Youtube
Jacob T
Updated on September 18, 2022Comments
-
Jacob T over 1 year
I'm new in the web development industry and I struggle to vertically and horizontally align a child div in a parent div. I'm trying to build a homepage with a full-width image with a slogan in the very middle of that image. This is my first attempt:
HTML:
<div class="img"> <div class="text">Here is my slogan</div> </div>
CSS:
.img { margin: 0px; padding: 0px; border-width: 0px; background-image: url("picture-1.jpg"); background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: 100% auto; background-color: black; min-height: 1024px; } .text { text-align: center; vertical-align: middle; height: 300px; padding: 175px;
}
I'm sure this is noobish code, but I'm a newcomer in this industry. Could you help me, please?
-
gota almost 7 yearsFlexbox takes care of this easily and has quite good coverage these days see here: caniuse.com/#search=flexbox
-
John Conde over 6 yearsThis question should have been migrated to Stack Overflow
-
-
Liam Kennedy about 7 yearsPutting this on in my library of code.