Search code examples
htmlcssimagebackground-image

How to correctly transfer background-image property in CSS in to HTML code without disrupting other CSS property?


I first used 'background-image' CSS property in a div to display the image due to the fact that it displays it properly as I wanted it:

  1. The image is below the nav bar (allowing the shadow to be shown).
  2. The image is an edge to edge but only accommodate less than 30% of the screen height according to the user screen size.
  3. The image allows a semi-transparent overlay for a title and description of the image.
  4. The image will fill(crop) to fit the canvas instead of stretching out or shrink.

How do I transfer the 'background-image' CSS property in to HTML as tag? As CSS doesn't support alt text as they're required for me to pass the exam.

I've tried to add a tag into HTML and removed background-image property from HTML (also ruleset name to accommodate the added img tag) However, it doesn't display it correctly as I wanted it to be.

== THE CODE ==

Old code:
CSS:

.image-container {
    padding-top: 10px;
    width: 100%;
    height: 48vw;
    min-height: 380px;
    max-height: 550px;
    background-image: url('/assests/DisplayImage.jpg');
    background-size: cover;
    position: relative;

.image-container .detail {
    position: absolute;
    bottom: 0;
    background: rgb(0, 0, 0);
    background: rgba(0, 0, 0, 0.5);
    color: #f1f1f1;
    width: 100%;
    padding: 0;
    text-align: center;
}

HTML:

    <div class="image-container">
        <div class="=detail">
            <h1>
                Title text
            </h1>
            <h3>
                Description
            </h3>
        </div>
    </div>

New Code:
HTML:

    <div class="image-container">
      <img scr=/assests/DisplayImage.jpg>
        <div class="=detail">
            <h1>
                Title text
            </h1>
            <h3>
                Description
            </h3>
        </div>
    </div>

CSS: (.image-container .detail remain the same)

.image-container img{
    padding-top: 10px;
    width: 100%;
    height: 48vw;
    min-height: 380px;
    max-height: 550px;
    position: relative;
}

I expect it to be like this: Expected (original result)
Instead I got this: The result of changing the code

In addition to this, I also wanted my image to be focused on the center of the image when the screen is resized instead of just cropping the bottom.

Thank you. This might be too specific, but I'm sure that this will help those who also used a CSS background image instead of HTML tag.


Solution

  • Check this pen
    There's nothing wrong in your code as I see.
    For aligning image to center use

     background-position: center;
    

    If you are using img tag for image use below properties.

    object-fit: cover;
    object-position: bottom;