简体   繁体   中英

How can I have child div without background image from parent div

I have two divs: One parent, one its child.

Parent has background image:

.parent{
  background-image: url('urltoimage/img.png');
  z-index: 1;
 }
.child{
  z-index: 2;
 }

but parent background image is still covering the background of its child. I want that child doesnot have background image

I also tried with z-index , but no success.

You have no image for the child, nor is any background color for the child specified. By inheritance property, the child inherits the parent attributes and overrides the parent attributes' values it specifies.

Your code could be something like this:

.parent{
  background-image: url('urltoimage/img.png');
  z-index: 1;
 }
.child{
   background-image: url('urltoimage/CHILD_IMAGE.png');
   // or you could specify background color
   z-index: 2;
 }

May be you are doing something wrong while writing the HTML part of the code but CSS looks fine.

HTML:

<div class="parent">
   <div class="child">
   </div>
</div>

Is this how you are doing it? Also don`t forget to add height and width in your css.

Example: a JSFiddle

If your child div has no background settings, it's natural that its' parent div background will show through. If you are trying to create the effect of cutting out the area of the child's div from the parent div. Then, you might have to use a different approach. One example might be to set the child's background to the same as the its' parents' parent's background. Otherwise, what has been mentioned about setting the dimensions and/or background of the child's div by others on this post will be your only recourse.

Here's a thought, can you use a .png image file for the parent's background-image that has a transparent area where the child div will be positioned?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM