Set the background of the div element behind the image

I am trying to create a layout where the div color matches the size of an image behind it, with the image moving slightly on hover. Here is my code:

<div class="row text-center about__gallery">
  <div class="col-xs-12 col-sm-4">
    <div class="about__gallery--first img">
      <img />
    </div>
  </div>
   .
   .
   .
</div>

Here is the SCSS for achieving this effect:

.about__gallery{
  margin-top: 5%;
  .img{
    background-repeat:no-repeat;
    background-size:cover;
    width:70%;
    height:230px;
    margin-bottom: 15%;
    img{
      z-index: 3;
    }
    &:before {
      position: absolute;
      content: " ";
      display: block;
      width: 70%;
      height: 230px;
      background-color: $color-blue;
      z-index: -100;
    }
  }
  .
  .
  .

The result I am getting does not match what I want. Here is the full code snippet:

<div class="row text-center about__gallery">
  <div class="col-xs-12 col-sm-4">
    <div class="about__gallery--first img">
      <img class="about__gallery__img--bg" />
    </div>
  </div>
  <div class="col-xs-12 col-sm-4">
    <div class="about__gallery--second img">
      <img class="about__gallery__img--bg" />
    </div>
  </div>
  .
  .
  .
</div>

And here is the corrected SCSS code:

.about__gallery{
margin-top: 5%;
margin-bottom: 10%;
.img {
    position: relative;
    margin-bottom: 15%;
    img {
        width: 100%;
        height: auto;
    }
    &:before {
      position: absolute;
      top: 0;
      left: 0;
      content: " ";
      display: block;
      width: 100%;
      height: 100%;
      background-color: $color-blue;
      z-index: -100;
    }
}

.about__gallery--first{
     margin-left: 45%;
     margin-bottom: auto;
     img.about__gallery__img--bg{
       content:url("../img/aboutus_pic1.png");
       width: 100%;
     }
   }
   .
   .
   .

You can view the final result here:RESULT

This is the design I am aiming for:GOAL

I have also tried adding hover effects which are not working as intended. Check out my codepen here.

Answer №1

If I were making changes, the first thing I'd do is remove the fixed height/width values you've set and let the container adapt to the image size. Then, it's important to determine the correct position for the pseudo-element relative to the container's position (which should be set to relative). You can see a working example here.

<div class="row text-center about__gallery">
    <div class="col-xs-12 col-sm-4">
        <div class="about__gallery--first img">
            <img src="http://placehold.it/250x250" />
        </div>
    </div>
</div>

.about__gallery {
    margin-top: 5%;

    .img {
        position: relative;
        margin-bottom: 15%;

        img {
            opacity: 0.8; // used to highlight the blue background
            width: 100%; 
            height: auto;
        }

        &:before {
            position: absolute;
            top: 0;
            left: 0;
            content: " ";
            display: block;
            width: 100%;
            height: 100%;
            background-color: $color-blue;
            z-index: -100;
        }
    }

    &--first {
        margin-left: 45%;
    }
}

Answer №2

Whenever I work on CSS, my go-to tool is Chrome Inspect Element. It helps me locate the specific element I want to modify and experiment with changing its background color. By looking at the CSS tab in CIE, I can easily identify which class is being affected and then simply apply that class in my internal or external CSS file. Using an image as a background can also add a nice touch to your design!

I recently customized the background color of the page we are currently working on - it's looking great now!

.so-header~.container {
background-color: #ccc;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best approach for implementing a CSS reset across multiple websites with different content?

As I work on a page that will be displayed across numerous websites beyond my control, shown within a jQuery UI dialog window using $.load(), the content is vulnerable to the CSS directives set by each individual site. To prevent conflicts, I have made sur ...

Creating a variety of themes with unique color palettes for Angular Material along with custom-designed components

One of the goals for my app is to have multiple themes, including Angular Material themes, with the ability to define custom colors for specific components and elements that are not part of Angular Material. It's important that when I change a theme, ...

Even with a correct XPath and the element present, Webdriver inexplicably throws a NoSuchElementException

There are 20 Google review score elements on a page like this. https://i.sstatic.net/9ErFS.png The XPath for each element is: //ol/div[2]/div/div/div[2]/div[%s]/div/div[3]/div/a[1]/div/div/div[2]/div/span To extract the review counts using Python and W ...

Reorder children in a column layout with the top and bottom child elements reversed

I am attempting to create a layout using flex-direction: column-reverse in order to swap the positions of button 1 and button 2 without modifying the HTML: <button>2</button> <button>1</button> Unfortunately, I'm encountering ...

material-icons appear differently when letter-spacing is applied in iOS browsers

To display levels using star icons from angular material, I wanted the stars to be shown next to each other. I attempted to achieve this by applying letter-spacing: -0.25rem;, but unfortunately it did not render correctly on iOS platforms (resulting in s ...

Understanding the differences between jquery's addClass method and the .css()

After creating a function to set a background on a click event, I encountered an issue. I attempted two different methods, expecting both to be successful. However, only the .css() version worked while the addClass method failed. Why is this happening? fu ...

Combining the background images of two separate <div> elements results in a deeper shadow effect than when they are individually displayed

Encountering an issue with overlapping background images that results in a darker shadow where they intersect, causing an uneven appearance. The problem arises with a flexible height box containing semi-transparent background images designed to create att ...

Sticky Sidebar Attached to Parent Container with Smooth Sliding Effect

Is it possible to have my sidebar push the content across when opened, while keeping the fixed navigation relative to its parent element instead of the viewport? The sidebar works fine in Firefox but breaks out of the parent in Chrome. Link to JSFiddle & ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

Interactive Dropdown-Buttons dynamically inserted

I have been utilizing a third-party library called Materializecss from this link: My issue arises when attempting to create a Dropdown feature upon clicking a button. It works perfectly fine when I manually place the button in the HTML and click on it, tr ...

How to create a stunning pixel pattern overlay on a website section

I've been exploring how to add a pixel pattern overlay onto a website section similar to what's done on this site: (over the background video image at the top and the image in the bottom section). I'm sure it's a simple process, I jus ...

Optimal method for arranging Vue components

When deciding where to position a child element, should it be done within its own CSS scope or from the parent? In the scenario provided below, would it be more effective to use margin-left: auto; on the parent element or the child element (both options a ...

HTML is appearing as unformatted text on the screen

I am utilizing deta for rendering cloud-based HTML content. Below is the code snippet in use: from deta import Deta from fastapi import FastAPI, Request, Response, Form, File, UploadFile from fastapi.templating import Jinja2Templates from fastapi.response ...

Inject the HTML code into a bash script and perform operations on it

Could someone help me with a bash scripting question? I'm new to this, so I may have missed it if it's already been answered. I want to pass the html source code of a web page to my script, which will then modify or scrape the web page of its HT ...

Integrate the element offset into jQuery's offset calculations

I'm new to utilizing jQuery and currently facing a challenge in determining the correct offset for a specific div element within the body. My goal is to make this particular div stick to its position as I scroll down past its designated top offset. A ...

Preview images in the Image Carousel bullet lineup

I've created an awesome image carousel using HTML and CSS. The carousel includes three bullets at the bottom that display a preview image when hovered over. Currently, there is a transition effect as the picture slides up and down. Is there a way to m ...

Can a faulty image be cached?

Is there a way to ensure that the browser caches invalid or broken images so that when they are re-fetched, the loading time is immediate? I am particularly interested in two scenarios: 1) The first scenario involves trying to load an image from a URL co ...

Trouble with executing select query on connected tables in MySQL

$sql=mysql_query("SELECT b.book_id,u.user_id,user_name,book_name,review_date,book_rating,review FROM tbl_books b,tbl_user u,tbl_book_reviews br WHERE b.book_id=br.book_id AND u.user_id=br.user_id ...

Creating a function that allows for the dynamic addition of rows in Angular with

I am currently working on implementing search and filter functionality, which requires adding rows dynamically. With hundreds of fields to filter, my boss has decided to organize them in dropdown menus (such as Manager, City, and Name in this example). The ...

Using Docker Compose to orchestrate a Node.js project

I am currently in the process of updating a node project that was developed using nuxt, and I am working on creating a DockerFile and corresponding docker-compose for it. While the build is successful, I encounter this error when trying to execute docker- ...