1

I have a div containing an image having a width of 30%. There's also an absolutely positioned div containing some text on top of this. I was able to horizontally align the text using the text-align:center property. But, how can I align the same text vertically as well, so that the text sits in the middle of the picture. vertical-align: middle seems to be not working in this case. The HTML and CSS are given below:

HTML

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" />
</head>
<body>
    <div class="container">
        <div class="image">
            <img src="http://goo.gl/hPGFvG"  />
        </div>
        <div class="text">
            <p>TEXT</p>
        </div>
    </div>
</body>
</html>

CSS

html {
    height: 100%;
}

body {
    height: 100%;
    margin: 0;
    font-family: 'Segoe UI', Arial, sans-serif;
}

p {
    margin: 0;
}

img {
    display: block;
}

.container {
    position: relative;
    width: 30%;
    min-width: 320px;
}

.image {
}

    .image img {
        margin: 0 auto;
    }

.text {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    text-align: center;
}

1 Answers1

2

If you feel like tweaking around, I think the quickest for you is to take out your calculator and set the top attribute at the negative of the half of your image's height.

For example : if your image has an height of 300px, then :

.text{
position : absolute;
top : -150px;
}

Be careful, you can't use vertical-align:middle everywhere, there are plenty of links about this, you should check this : Centering in the Unknown.

Good luck!

astrodedl
  • 210
  • 3
  • 8