How to Inherit grandparent CSS not parent?

孤人 提交于 2019-12-05 10:38:09

This would be with using javascript and jQuery:

CSS

body {
   background: url("Background 1");
}
#div1 {
   background: url("Background 2");
}
#child1 {
   background: url("Background 1");
}

JS

$(function() {

  function positionBackground() {

     var myChild1   = $("#child1");
     myChild1.css({
        backgroundPosition : "-" + myChild1.offset().left + "px -" + myChild1.offset().top + "px"
     });
  }

  positionBackground();

  $(window).resize(positionBackground);
});

Here is the fiddle: http://jsfiddle.net/gMK9G/

I don't think you'll be able to change the way that styles are inherited, that said, you shouldn't really need to.

This is a little rough, but you could use the same image on the child div as you're using on the body and just play with the background positioning to line it up.

Working Example

body {
    background: url("Background 1");
}
#div1 {
    background: url("Background 2");
}
#child1 {
    background: url("Background 1");
    background-position: 0px -125px; /* adjust as needed */
}

UPDATE 2 Elements in the DOM Cannot share the same background image, you can maybe apply the background image and position them exactly so that it looks like they are, but in reality it is not possible.

As far as I am aware this is not currently possible because css only has inherit and inherit "inherits" from it's parents and there is no way to customize that. Of course javascript can do this easily and I will provide a jQuery example only because you have the tag.

$('.inherit-grandparent').each(function( element ) {
    var $this = $(this),
        property = $this.attr('grandparent-property'),
        value = $this.parent().parent().css(property);
    if(property && value) $this.css(property, value);
}); 

Usage

<div class="inherit-grandparent" grandparent-property="background"></div>

Demo: http://jsfiddle.net/aKHfr/

So not only will this solve your problem, but it's dynamic so you can use it on any element and request any property.

Update:

Here is a jQuery Plugin version, if you would prefer that.

jQuery.fn.inheritGrandparent = function( property ) {
    var $this = $(this),
        value = $this.parent().parent().css(property);
    if(property && value) $this.css(property, value);
}; 

Usage:

$('#test').inheritGrandparent('background');

Demo: http://jsfiddle.net/aKHfr/2/

Happy Coding!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!