pig's diary

何でも忘れるので万年初心者ね

CSS3時代にstylus

stylus を使ってコードが短くなった例。

iPhone HOME みたいな配置がしたかった(アイテムが出てからリサイズしてみてください) のですが、CSS が長ったらしくなりわけが分からなくなりました。

HUNDRED = 100%
itemHeight = 240px

/* TODO: Use stylus iterator */
@media only screen and (max-width: 749px)
  .word:nth-child(1)
  .word:nth-child(2)
    top 0
  .word:nth-child(3)
  .word:nth-child(4)
    top itemHeight
  .word:nth-child(5)
  .word:nth-child(6)
    top itemHeight * 2
  .word:nth-child(7)
  .word:nth-child(8)
    top itemHeight * 3
  .word:nth-child(9)
  .word:nth-child(10)
    top itemHeight * 4
  .word:nth-child(11)
  .word:nth-child(12)
    top itemHeight * 5

  half = (HUNDRED / 2)
  quoter = (half / 2)
  .word:nth-child(2n-1)
    left half + quoter
  .word:nth-child(2n)
    left quoter

@media only screen and (min-width: 750px) and (max-width: 999px)
  .word:nth-child(1)
  .word:nth-child(2)
  .word:nth-child(3)
    top 0
  .word:nth-child(4)
  .word:nth-child(5)
  .word:nth-child(6)
    top itemHeight
  .word:nth-child(7)
  .word:nth-child(8)
  .word:nth-child(9)
    top itemHeight * 2
  .word:nth-child(10)
  .word:nth-child(11)
  .word:nth-child(12)
    top itemHeight * 3

  half = (HUNDRED / 3)
  quoter = (half / 2)
  .word:nth-child(3n-2)
    left (half * 2) + quoter
  .word:nth-child(3n-1)
    left half + quoter
  .word:nth-child(3n)
    left quoter

@media only screen and (min-width: 1000px)
  .word:nth-child(1)
  .word:nth-child(2)
  .word:nth-child(3)
  .word:nth-child(4)
    top 0
  .word:nth-child(5)
  .word:nth-child(6)
  .word:nth-child(7)
  .word:nth-child(8)
    top itemHeight
  .word:nth-child(9)
  .word:nth-child(10)
  .word:nth-child(11)
  .word:nth-child(12)
    top itemHeight * 2

  half = (HUNDRED / 4)
  quoter = (half / 2)
  .word:nth-child(4n-3)
    left (half * 3) + quoter
  .word:nth-child(4n-2)
    left (half * 2) + quoter
  .word:nth-child(4n-1)
    left half + quoter
  .word:nth-child(4n)
    left quoter

たすけてstylus !

HUNDRED = 100%
itemHeight = 240px
grid-positioning(COL, MAX=12) 
  ROW = MAX/COL
  half = (HUNDRED / COL)
  quater = (half / 2)

  for index in 0..MAX
    if index % COL == 0
      more = '+'+ (index+1)
      .word:nth-child(n{more})
        top (itemHeight*index / COL)
  for index in 0...COL
    more = COL - index - 1
    .word:nth-child({COL}n-{more})
      left HUNDRED - (half*index + quater)

@media only screen and (max-width: 749px)
  grid-positioning(2)

@media only screen and (min-width: 750px) and (max-width: 999px)
  grid-positioning(3)

@media only screen and (min-width: 1000px)
  grid-positioning(4)

人々がstylus を忘れることは決してないだろう。

github

  • はい、もっと短くなるかも知れません
  • 一部CSS3 自体の機能で短くしてます(はじめ、知らなくて)
  • media-query 行で変数を展開できないバグがある。( issue269
  • その他、計算が思うようにできなくて地味に時間がかかった。
  • 変数が値に展開されないときは、「{}」囲うといい場合がある。

追記

  • grid-positioning(5) が動かない・・・なんか間違えているみたいです。

追記

  • 修正。これでいくつが来ても動くと思うぞ