Home > Enterprise >  Can you make whole background-image height show using an overlay image with side-by-side text in CSS
Can you make whole background-image height show using an overlay image with side-by-side text in CSS

Time:11-10

I have the following HTML/CSS code for displaying an image and a block of text side by side over a full-width background image.

<section style="position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url("background.jpg"); background-repeat: no-repeat; background-size: 100%;">

<img style="float: left; width: 50%; margin: 1%;" src="overlay-image.jpg" alt="Image overlaid on background image.">

<p style="color:white;">Text overlaid on background image.</p>
<section>

The trouble is, only the top portion of the background-image that is overlaid by the text shows.

Is it possible to make the background image show its vertical portion as much as the overlaid image height?

I've tried "background-size: cover". In Google Chrome Version 107.0.5304.88 (Official Build) (64-bit), and Mozilla FireFox 106.0.5 (64-bit), the result is the same as above; only the portion of the background image overlaid by text, not image, show.

CodePudding user response:

You are using float and floated elements do not add to the height of the container/parent element, hence your section background is depending on your p tag height, either add a static height to the section or remove the float property and use flexbox instead.

CodePudding user response:

Using the answer @18jad gave, I tested the following code.

<section style="position: static; background-color: black; margin: 0; padding: 0; width: 100%; background-image: url("background.jpg"); background-repeat: no-repeat; background-size: 100%; display: flex;">

<img style="flex: 50%; margin: 1%;" src="overlay-image.jpg" alt="Image overlaid on background image.">

<div style="flex: 50%; text-align: left; margin: 1%;">
<p style="color:white;">Text overlaid on background image.</p>
</div>
<section>

It works as desired: the whole background image shows! Thanks to @18jad!

  • Related