Gaurav Aggarwal Gaurav Aggarwal - 2 months ago 23
Less Question

&extend showing no matches when element exists

I am using less css for a basic website when i was trying to use

&extend
of less its showing no matches element when the element do exists.

I created a dummy environment same problem exists. Here is my code

style.less

@import 'style1.less';

@colorgreen: #00ff00;
@colorred: #ff0000;
@fontsize: 20px;
@bsolid: solid;
@bdash: dashed;

.container{
border:1px @bsolid #ccc;
padding: 10px;
.myclass{
border: 1px @bdash #ccc;
padding: 10px;
h1{
color: @colorred;
font-size: @fontsize;
}
p{
color: @colorred;
font-size: @fontsize;
}
}
}
.extend{
border: 1px solid #ccc;
padding: 10px;
h2{
color: green
}
p{
&:extend(h2);
font-style: italic;
}
}


HTML

<div class="container">
<div class="myclass">
<h1>Second Heading</h1>
<p>LESS enables customizable, manageable and reusable style sheet for web site.</p>
</div>

<div class="importClass">
<p>This is imported CSS.</p>
</div>

<div class="extend">
<h2>First in extend</h2>
<p>Second in extend</p>
</div>
</div>

Answer

As the official Less Website indicates, the Less compiler looks at the compiled CSS selector when processing extend.

Essentially the extend looks at the compiled css, not the original less.

So, when trying to extend a nested selector, we should provide the full selector in the extend and not just the inner selector. In the example in question, the compiled CSS selector would be .extend h2 and so when the extend statement has only h2 provided as input, it wouldn't match and not output anything.

So, the below would compile successfully and work as per expectation.

.extend{
  border: 1px solid #ccc;
  padding: 10px;
  h2{
    color: green
  }
  p{
    &:extend(.extend h2);
    font-style: italic;
  }
}

When compiled, it would result in the below CSS:

.extend {
  border: 1px solid #ccc;
  padding: 10px;
}
.extend h2,
.extend p {
  color: green;
}
.extend p {
  font-style: italic;
}