I'm trying to create a responsive, full-page width hero img/banner, with some text on top.
Because I want a div on top of the img/banner, containing some text, I've chosen to use the CSS background-image
property (rather than an HTML <img>
element) for the image (I'm trying to avoid using position: absolute
if possible).
After a lot of messing about, I seem to have found a great solution to get the background-image
property to behave just like an HTML <img>
element (which is exactly how I want the img to behave when resized)...
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.bg-img {
background-image: url('https://www.bbva.com/wp-content/uploads/2016/12/Carl-Sagan-BBVA-1920x0-c-f.jpg');
background-size: contain;
background-repeat: no-repeat;
width: 100%;
padding-top: 40.57%;
/* (img-height / img-width * width) */
/* (779 / 1920 * 100) */
}
...however, this 'roundabout' solution to get the image to behave, calls upon padding to increase the height of the bg-image container, which forces the <div>
containing my text content off of the image and further down the page :(
Is there any way to resolve this without using absolute positioning on the text div to get it to sit over-top of the bg-img?
I put everything into a pen to make it easier to play with: https://codepen.io/Hacktinium/pen/VwWRBdg
Thanks in advance
Not sure if understood 100% your desired outcome, if you want the text to be at the top of the image without using an <img>
tag, why don't put the content, and the image inside a wrapper but in different divs?
I've created this pen as an example: https://codepen.io/mvuljevas-the-selector/pen/zYzbJgO