How to refer to two previous elements / tags / classes with LESS

安稳与你 提交于 2019-12-11 06:33:58

问题


I have this html markup:

<figure class="about half">
    <figcaption class="head_section">
        <h3>About</h3>
    </figcaption>
</figure>

and this LESS set up:

 figure {
    //some style

    &.half {
      width: 48%;
    }

    figcaption {

      h3 {

        .about & & {
          // what i need to do but isn't working
        }
      }
    }

    &.about {

      h3 {
        // some style i have which is working
      }
    }
  }

So, my question is how to refer two previus class of figure.about so as not to be out of style h3. I hope that is clear... Much thx.


回答1:


I'm still not sure I understand what you are trying to achieve here, as you haven't supplied a desired css output. The idea I kinda managed to extract from your question would be a css that looks like this:

figure {
  /* some style */
}
figure.half {
  width: 48%;
}
figure.about figcaption h3 {
  /* what i need to do but isn't working */
}

is this correct?

Here is a way to get this to work with &:

figure {
    /* some style */
    &.half {
        width: 48%;
    }
}
figcaption {
    h3 {
        .about & {
            /* what i need to do but isn't working */
        }
    }
}

The thing here is that the & returns the "path" for all nesting levels above, so you need to construct the nesting rules with exactly the ones you want to use (in our case I moved the figcaption out of the figure rule). So this should give you the selector appearance you want. However, the structure of the nested rules will often depend on the way you want to use @variable inheritance and scope referencing and in some cases it just makes it hard to build the structural selector exactly the way you want, but then there will almost never be the need for including the whole html structure in your selector - and just as in your case figure.about h3 will work just as well as figure.about figcaption h3, as you probably will not add more h3 elements into the figure container.



来源:https://stackoverflow.com/questions/16034348/how-to-refer-to-two-previous-elements-tags-classes-with-less

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