Home > OS >  How to change background color but keep the background image from parent element in css
How to change background color but keep the background image from parent element in css

Time:11-21

I would like to define the background image for whole table with DNA image and I want to use default color gray for whole table but some of columns I need with white color.

If I try to override the background color, the DNA image is gone.

I have tried this one with bootstrap:

HTML:

<div class="container mt-3">

  <div class="row">
    <div class="col-6 col-white">col1</div>
    <div class="col-6 col-white">col2</div>
  </div>
  <div class="row">
    <div class="col-6">col3</div>
    <div class="col-6">col4</div>
  </div>
</div>

CSS:

body{
  background-color: yellow;
}
.container{
  background-color: gray;
  background-image: url('https://raw.githubusercontent.com/skoruba/css-bg-img/main/dna (1).png');
  background-repeat: repeat-y;
  background-position: 50px 0;
}

.col-6 {
  padding: 20px;
}

.col-white {
  background-color: white;
}

Demo: Grid2

Expected:

Grid

How can I override only background color, but not background image as well?

CodePudding user response:

You could just add the DNA as a repeating background to an after pseudo element on the container, positioning it just to the right a bit.

This will go over everything without affecting anything else's positioning.

You need to set the position of the container though so that its pseudo element can position itself in relation to that.

Add this to the CSS:

.container::after {
   content: '';
   position: absolute;
   left: 50px;
   top: 0;
   width: 30px;
   height: 100%; 
  background-image: url('https://raw.githubusercontent.com/skoruba/css-bg-img/main/dna (1).png');
  background-repeat: no-repeat repeat;
  background-position: center center;
  }

and add position: relative to the .container but remove the background-image from there.

  • Related