I've been fiddling with Stylus for a bit now, and wanted to accomplish something with a mixin that feels like it should be possible even though I can't figure it out. Specifically, I'd like to write a mixin that styles the parent of the element to which the mixin is applied. I can never remember the right syntax for vertically centering something with a pseudo-element, for example, so I'd like to have a handy-dandy mixin for it; but I'd ideally like to apply it to the element to be centered, and the pseduo-element belongs on that element's parent.

Not too surprisingly, this didn't work:

vertical-middle()
    display inline-block
    vertical-align middle

    &
        font-size 0

        &::before
            content ''
            display inline-block
            height 100%
            vertical-align middle


.nav-wrapper
    .nav
        vertical-middle()

...and in fact may have confused Stylus a bit, since the CSS it generated had two .nav-wrapper .nav blocks:

.nav-wrapper .nav {
  display: inline-block;
  vertical-align: middle;
}
.nav-wrapper .nav {
  font-size: 0;
}
.nav-wrapper .nav::before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

My guess is that I'd get less grief with a block mixin, but I get the sense that then I'd wind up passing the usual styles for .nav and .nav-wrapper to it and it seems like that way lies pain.

有帮助吗?

解决方案

Using a block mixin is the best way in your case:

vertical-middle($sel)
  {$sel}
    display inline-block
    vertical-align middle
    {block}

  font-size 0

  &::before
    content ''
    display inline-block
    height 100%
    vertical-align middle


.nav-wrapper
  +vertical-middle('.nav')
    foo: bar

You will be able to do that your way when Stylus gets support for more powerful parent references - https://github.com/LearnBoost/stylus/issues/1240

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top