It’s quite common to use background image and place text above it but it’s also possible to use image in foreground and place text above foreground image overlay. You can also horizontal center or vertical center the text as explained in the article.
So our page contains a piece of HTML as follow:
1 2 3 4 | <div class="img-container"> <img src="sample-image.png" /> <div class="caption">A sample text</div> </div> |
Placing text above foreground image in html
First of all our image container needs relative positioning and you can add other CSS rules as per your requirements:
1 2 3 | .img-container { position: relative; } |
You can also apply float: left;
in order to collapse its block-level descendants to the width of the element or simply give it a display: inline-block;
which will allow it to have its block-level contents contained, and remain in the document flow. All depends on page requirements.
Now time to apply some CSS rules to caption or text part inside image container. The following CSS rules will place the text or caption above foreground image as well as make horizontal center within image container.
1 2 3 4 5 6 7 | .caption { position: absolute; //absolute positioning required top: 10%; //adjust the vertical distance left: 0; width: 100%; text-align: center; } |
You can edit top
attribute’s value to vertical align the text and a value around 45%
would make it vertically center. So using the CSS rules above you can maintain horizontal and vertical centering while Placing text above foreground image in html while maintaining page responsiveness.