Skip to content

Parent Selectors should have targets #1075

Open

Description

@scottrippey

When creating a Parent Selector rule, everything before the & gets prepended to the outermost scope.

The feature could be greatly improved by allowing for "parent targeting", where you could apply the parent selector to a specific parent (in the case where you have deeply nested selectors).

The syntax for this feature is probably the biggest hindrance, so I would love to start a discussion on the possibilities.

Activity

  1. scottrippey commented on Dec 13, 2012

    @scottrippey
    Author

    Example usage:

    .main-content {
        .button {
            .button-icon {
                background-image: @button-icon;
                (.button):hover { background-image: @button-icon-hover; }
                (.button).focus { background-image: @button-icon-focus; }
                .ie8 (.main-content) { background-image: @button-icon-ie8; }
            }
        }
    }
    

    This may be a contrived example, but I have several real-world scenarios where such a syntax would be a life saver.

  2. matthew-dean commented on Dec 13, 2012

    @matthew-dean
    Member

    There's a variety of solutions in LESS to handle this. You can assign variables and use those as part of selector chains (new in 1.3.1 I think). The & is not really a parent selector in the CSS4 sense of the term. It literally just appends the inherited selectors to wherever you place them.

  3. matthew-dean commented on Dec 13, 2012

    @matthew-dean
    Member

    I usually just end up writing these code blocks like this:

    .main-content {
        .ie8 & { background-image: @button-icon-ie8; }
        .button {
            &:hover { background-image: @button-icon-hover; }
            &.focus { background-image: @button-icon-focus; }
            .button-icon {
                background-image: @button-icon;
            }
        }
    }
    
  4. scottrippey commented on Dec 13, 2012

    @scottrippey
    Author

    I do the same thing -- I duplicate my nested blocks with the overrides. In a real-world scenario, this results in an unmanageable amount of duplication.
    FYI, in your example, the background-image needs to be applied to the .button-icon, so you'd have way more duplication.

  5. scottrippey commented on Dec 13, 2012

    @scottrippey
    Author

    Can you explain "assign variables and use those as part of selector chains"?

  6. matthew-dean commented on Dec 13, 2012

    @matthew-dean
    Member

    I'm probably wrong about that quote, so probably shouldn't try to explain it. That is, I haven't tried it personally.

    So, it looks like what you want to do is modify a selector in the inherited chain. How would this work in this case?

    .button {
    .main-content {
        .button {
            .main-content {
                .button-icon {
                    background-image: @button-icon;
                    (.button):hover { background-image: @button-icon-hover; }
                    (.button).focus { background-image: @button-icon-focus; }
                    .ie8 (.main-content) { background-image: @button-icon-ie8; }
                }
            }
        }
    }
    }
    

    It's messy CSS, but it's perfectly valid CSS.

  7. scottrippey commented on Dec 13, 2012

    @scottrippey
    Author

    That's a good example ... if the "parent target" matches multiple items, we'd want to choose just one. Choosing the "closest" one is my first reaction. But I think this would be an edge case.

  8. scottrippey commented on Dec 13, 2012

    @scottrippey
    Author

    So far, I've scratched down several attempts to invent a syntax that I like ... and the parenthesis so far is my favorite. It seems readable, and definitely catches your attention to highlight that this is no normal selector.

    The only problem -- does this interfere with any existing CSS selector rules? Looking at the less parser, I see that a selector element can match /\([^()@]\)/ which means it's already being parsed correctly. I don't know if these parenthesis are valid.

    I just realized that the parenthesis syntax looks almost exactly like a mixin definition ... with the exception of the class dot .. So maybe it's not a good idea. Feedback?

  9. lukeapage commented on Dec 14, 2012

    @lukeapage
    Member

    Your use case sounds like what is discussed in #965 .. what do you think?

    Bearing in mind & is quite powerful already and we are bringing in :extend() in 1.4.0, it seems to me if the only thing missing is being able to call a mixin that adds selectors to your selector chain, then if we decide to add that functionality it should be as simple as possible.. the more we add to selectors, the more complicate less gets to learn and understand.

  10. matthew-dean commented on Dec 14, 2012

    @matthew-dean
    Member

    Yeah, I feel like, unfortunately, the logic gets a little messy, and like @agatronic, there may be other ways to fill in what you want in the future.

  11. scottrippey commented on Dec 14, 2012

    @scottrippey
    Author

    I agree. This over-complication is a result of a very complicated LESS structure, and time would probably be better spent in simplifying the LESS code instead of introducing a very complicated syntax.

  12. matthew-dean commented on Feb 1, 2013

    @matthew-dean
    Member

    I'm going to re-open this. We've seen variations on this idea (such as #1154), and I feel like there's a possibility of a solution.

    That is, there are times when people have a logical stack of elements, but don't necessarily want to inherit the entire stack in their output.

    Also, there are times when people want to inherit SOME of the stack, but not all of it.

    I think we can all agree that we don't want messy syntax, but I'd like to see a variety of ideas. As we've explored here, targeting by name seems problematic. But we could also target by level:

    .main-content {
        .button {
            .button-icon {
                background-image: @button-icon;
                &{2}:hover { background-image: @button-icon-hover; }
                &{2}.focus { background-image: @button-icon-focus; }
                .ie8 &{3} { background-image: @button-icon-ie8; }  // In this case, &{3} is the same as & because it goes to top
            }
        }
    }
    

    Basically, step "up" the inheritance tree to the level we want to inherit / append to the current selectors.

    Or, something like, maybe "breaking" the inheritance and starting over, without having to move the class outside of the block. I dunno, like:

    .grandparent {
      .parent {
        /.child {   // Ordered logically, but outputs cleaner CSS
          background: white;
        }
      }
      background: blue;
    }
    

    or, borrowing from the top example:

    .grandparent {
      .parent {
        &{0}.child {   // inherit NONE of the parents
          background: white;
        }
      }
      background: blue;
    }
    

    Both outputting:

    .grandparent {
      background: blue;
    }
    .child {
      background: white;
    }
    

    Thoughts?

  13. lukeapage commented on Feb 4, 2013

    @lukeapage
    Member

    I like it. I prefer my suggestion of &1 or @Soviut &(1). I think probably that is my current winner.

  14. 110 remaining items

  15. matthew-dean commented on Jun 15, 2018

    @matthew-dean
    Member

    No it wasn't impossible functionality wise. Sure, i had to add an extension method but it was considered impossible because less couldn't look up because it's compiled and doesn't know about it's surroundings (html).

    Then that's just someone completely misunderstanding your example. No, your example is simple and I understand what you're going for. It's a similar request to the "capture" and "replace" examples throughout this thread, you're just demonstrating using different syntax.

    I wonder if the easiest isn't just:

    1. Allowing assigning & to a variable, or as a param to a function.
    2. Using the replace function.
    3. Adding an "at-root" type selector (^?)

    Then you could just do:

    .grandparent {
      .something {
        @grandparent-hover: replace(&, '.grandparent', '.grandparent:hover');
        ^ @{grandparent-hover} {
          color: red;
        }
      }
    }

    It's a few features in one, which is why this thread's discussion has been so complex, because when people raise examples, they're talking about several features for one use case.

  16. matthew-dean commented on Jun 15, 2018

    @matthew-dean
    Member

    Oops, I had this tab open on my browser and didn't see the vitriolic comments that happened in the interim.

  17. matthew-dean commented on Jun 15, 2018

    @matthew-dean
    Member

    Or build in replace? ...
    🤔

    .grandparent {
      .something {
        // & currently = .grandparent .something
        &:visited {
          color: yellow;
        }
        &(.grandparent; .grandparent:hover) {
          // & now = .grandparent:hover .something
          color: red;
          &:visited {
            color: blue;
          }
        }
      }
    }
    
    // output CSS
    .grandparent .something:visited {
      color: yellow;
    }
    .grandparent:hover .something {
      color: red;
    }
    .grandparent:hover .something:visited {
      color: blue;
    }

    Spitballin'... seems more robust and clear than numerical index referencing, which can be ambiguous. Just selector search / replace built into a &() function.... one downside is we may want other "& alteration" extensions in the future?

    This still requires the feature additions of:

    1. Passing selectors to functions.
    2. & as a function
  18. seven-phases-max commented on Jun 15, 2018

    @seven-phases-max
    Member

    Or build in replace? ...

    Or explicitly declaring a placeholder within the selector of interest to not make potentially independent code to guess, know or hack specific element name or position (where not necessary).

    For my taste the Sassish @at-root thing has typical hardcoded backdoor problem (of being easily broken):

    .foo {
       @at-root .bar {color: red}
    }

    then in a far away galaxy:

    .baz {
        @import "foo.less"; // oops
    }
  19. matthew-dean commented on Jun 15, 2018

    @matthew-dean
    Member

    Or explicitly declaring a placeholder within the selector of interest to not make potentially independent code to guess, know or hack specific element name or position (where not necessary).

    That example looks a bit confusing to me, although I think that's essentially "capture" and "replace"? I couldn't tell. Like this but only with explicit names? If that's the case, that's also reasonable to me.

    For my taste the Sassish @at-root thing has typical hardcoded backdoor problem (of being easily broken):

    I don't disagree, that's why I wrote a second example that doesn't require it. I don't think it's completely unnecessary, though. I just think it shouldn't be built into a potential solution here. I think "in-place alteration of & inheritance" is probably better (than something using an @at-root-like solution).

    But, to be clear, as I mentioned above, capture/replace also seems appropriate.

    @seven-phases-max One thing that might help this thread from just spinning its wheels forever and ever. Of these solutions: a) in-place alteration of &, b) capture/replace, c) other - Do you have a preference? Because part of the wheel-spinning is literally approach, not just syntax. If there was some consensus on approach, syntax might eventually gel here.

  20. momomo commented on Jun 15, 2018

    @momomo

    What's wrong with:

    css  = '' +
    '.body {  ' +
                                    
            '.main { ' +
                                    
                '.section {' +
                                    
                    '.article {' +
                            // --- Call made here! ---
                                    
                            // Climb up to .main, and then add the selectors inside the body below
                            'closest(".main", {' +
                                    
                                '&:hover {' +
                                    'background-color:red;' +   // Meaning that when you hover .main then .article will get background-color:red;
                                '}' +
                                    
                                '&.someclass {' +
                                    'background-color:blue;' +   // Meaning that when .someclass is added to .main then .article will get background-color:blue;
                                '}' +
                                    
                            '})' +
                                    
                            // Do note that purpose of climbing up is to style article, nothing else.
                                    
                        '}' +
                                    
                    '}' +
            '}' +
    '}';
                                    
    less.render( css ,function (error, output) {
            console.log('xxx');  console.log(output.css);
    });
    

    You can do a bunch of other stuff two.

  21. matthew-dean commented on Jun 16, 2018

    @matthew-dean
    Member

    @momomo

    What's wrong with:

    There's nothing particularly "wrong" with it. In fact, for a while now, Less has allowed functions to be called at practically any node. So you could likely do this as a Less @plugin. I wonder if that's not the best way to resolve this.

    But, as far as syntax, IMO it's not a good fit in the Less language, because there are a few oddities / outliers in that construction, such as wrapping selectors in quotes, and calling a function at the root. Which you CAN do and define functions for that purpose. So if you want to solve this as a plugin, you can do it today, without any Less syntax changes whatsoever. It would be called literally with:

    @plugin "closest";
    .body {
      .main {
        .section {
          .article {
            // This will parse, as there's nothing invalid about this syntax
            closest(".main", {
              &:hover {
                background-color: red;
              }
              &.someclass {
                background-color: blue;
              }
            });
          }
        }
      }
    }

    The only tricky part: whatever selector is returned by closest() will still have all the same merging rules applied. I still think that a plugin could manage to give the desired behavior.

  22. momomo commented on Jun 16, 2018

    @momomo

    @matthew-dean

    Exactly. Regarding the quotes not being ideal, I agree with you, however considering the complexity and time it has taken to resolve this issue using other means and the perceived downside of using quotes, I think it is basically a non issue, especially if we want to speed up the adding of such a functionality.

    Surely it can and should ideally be done prior to the plugin method kicking in (performance being one reason), but this could showcase the desired functionality and pave the way as it is not even clear right now, what the desired functionality should do. There's also a lot of other issues, syntax wise with Less that are far worse.

    Please contact me on opensource ATTT momomo DOTTT com and we can take it from there. I do not use Twitter unfortunately.

  23. matthew-dean commented on Jul 15, 2018

    @matthew-dean
    Member

    Per comment here, in discussion about how to "consume" a captured & selector, there was discussion about replacing & in-place, which then lead back to this issue. Since this is more in line, I thought I'd continue that here of what was being discussed, which was similar to what I mentioned at #1075 (comment)

    • &() - return in-place &
    • &(arg) - replace & with arg and return
    • &(arg1, arg2) - replace arg1 in & with arg2 and return as new &

    The tricky thing about that is: is it a modification of selector inheritance for all further children? Or is it just a modification for that particular selector? As in:

    .component {
      &(.foo) .child { // selector is now .foo .child ?
        & .grandchild { // is & now .foo .child? Have we altered it permanently? I would presume yes
        }
      }
    }

    Also, this would prevent things like:

    .something:not {
      &(.selector) {}
    }

    I'm not sure anyone would ever have reason to write that, but it's worth pointing out.

  24. sorcamarian commented on Oct 1, 2018

    @sorcamarian

    What about this approach:

    ^ - back one selector
    ^(x) - back x selectors
    (sign: "^" is inspired from: http://docs.emmet.io/ )

    #wrapper {
      .row {
    
       .text-side {
          h2{
            color : #000;
            }// h2
          .text-description{
              p{
                color : #333;
                mark{
                  background-color: green;
                  } // mark
                } // p
            } // .text-description  
        }
    
        ^ .image-side {
       // avoid 1 selectors: .row
          .image-block {
            ^(2) img{
            // avoid 2 selectors: .image-block .image-side
              width: 100%;
              } // img
            } // .image-block
          } // .image-side
    
      }// . row
    } // #wrapper
    

    Source: sass/sass#2193

  25. hawkerboy7 commented on Oct 27, 2023

    @hawkerboy7

    Hi.
    After about 5 years of no update on this issue, is there a solution for this ability to select / restrict the parent selector, that might not yet have been added in this issue?
    I've asked a question in discussions about this behaviour as well.

    This mixin's parent selector ~ & will select the whole tree up (which makes sense) though it should only (in this case) select its nearest ancestor for this :first-child:nth-last-child trick to style children (/siblings) based on children count.

    .with-count(@n, @content) when (@n > 1) {
    	&:first-child:nth-last-child(@{n}),
    	&:first-child:nth-last-child(@{n}) ~ & {
    		@content();
    	}
    }
  26. momomo commented on Nov 12, 2023

    @momomo

    I later implemented this myself into the less.js lib but I later on moved on from less to other solutions. Not sass either. I think my syntax was closest(.parentclass) { &.something { ... } }

  27. matthew-dean commented on Nov 13, 2023

    @matthew-dean
    Member

    @hawkerboy7 I think the reason this mostly didn't go anywhere is that needing to grab just the parent selector often indicates a structural or logic problem in your stylesheet. As in, there are probably other ways to get to the desired output.

  28. hawkerboy7 commented on Nov 13, 2023

    @hawkerboy7

    Hi @matthew-dean,

    Thank you for your answer!
    How would you structurally or logically resolve this situation?
    To me this seems to be a very normal and regularly used way of selecting.
    I am here to learn :)

  29. momomo commented on Nov 13, 2023

    @momomo

    @matthew-dean I think it is just your mind that has a structural or logical problem thinking that this is the only reason that it wasn't implemented. Like if you can target the nearest parent with & ... why not two parents, or higher ? If the goal is to manipulate an element I am defining stuff for, say for :hover higher up, why should I not define all of its logic in one place. Why force a different way or place of declaring things that affect this particular element.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions