3

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?

Update: I made a picture of what I intend: enter image description here

closed as off-topic by John Conde Jan 25 '18 at 15:41

  • This question does not appear to be about webmastering within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

2

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/

  • 1
    Putting this on in my library of code. – JustJohn Feb 7 '17 at 19:59
1

Try CSS Flexbox: display: flex; align-items: center;

Not the answer you're looking for? Browse other questions tagged or ask your own question.