2
3

More than 3 years have passed since last update.

よく使うけどちょっとニッチなcss

Last updated at Posted at 2020-03-10

よく使うけど、いつもググってるので、まとめました。

pタグの直後にulがある時のみ適応(隣接セレクタ)

style.scss
p + ul {
  margin-top: 50px;
}

pタグの直後にある要素がulタグじゃなかった場合はstyleが指定されない

親要素の直接の子要素のみに適応(親子セレクタ)

style.scss
p > ul {
  margin-top: 50px;
}

ある要素と同じ親要素に属し、後続に出現する要素にのみ適応(間接セレクタ)

style.scss
.list ~ .item {
  margin-top: 50px;
}

.listの後続に出現する、全ての.itemに反映される。

.main と .textどっちのclassも持ってる要素を指定

style.scss
.main {
 &.text {
   margin-top: 50px;
 }
}

//↓コンパイル後

.main.text {
  margin-top: 50px;
}

単純にclass名の追加→.main_textを指定

style.scss
.main {
 &_text {
   margin-top: 50px;
 }
}

//↓コンパイル後

.main_text {
  margin-top: 50px;
}

target="_blank"のついた要素にstyleを指定

style.scss
.button a[target="_blank"]::after {

}

ちなみに、タグに「target=”_blank”」を付与する場合「rel=”noopener”」を付けた方がいいらしい。

classを持ってないpタグを指定

style.scss
 p:not([class]) {
}

特定のclassを持ってないpタグを指定

style.scss
 p:not(.hoge) {
}

classとidを持ってないpタグを指定

style.scss
p:not([class]):not([id]) {
}

divタグ配下の全ての要素にstyleを適応

style.scss
 div * {
 margin: 10px;
}

&を組み合わせる-その1

style.scss
.sample {
    & + & {
        margin-top: 1em;
    }

    &,
    &--hoge {
        margin-top: 1em;
    }
}

  コンパイル後

.sample + .sample {
  margin-top: 1em;
}

.sample, .sample--hoge {
  margin-left: 1em;
}

使用例

style.scss

.page-top {
  &,
   a {
   margin-right: 10px;
}

  コンパイル後

.page-top,
.page-top a {
  margin-right: 10px;
}

classがpage-topのaタグに反映させたい時にも使用できる

&を組み合わせる-その2

style.scss
.hoge {
    &__sample {
    margin:0 auto;
        .test & {
        padding :10px;
        }
    }
}

  コンパイル後

.hoge__sample {
  margin: 0 auto;
}
.test .hoge__sample {
  padding: 10px;
}

.hoge__sampleの要素を使用しながら親のクラス名を別で指定し、特定の要素を追加したい時に便利

3番目のみ

style.scss
li:nth-child(3){
  margin-bottom: 20px;
}

2の倍数のみ

style.scss
:nth-child(2n)

奇数

style.scss
:nth-child(odd)
:nth-child(2n+1)

偶数

style.scss
:nth-child(even)
:nth-child(2n)

最後以外

style.scss
li:not(:last-child) {
    margin-bottom: 20px;
}

最初と最後のみ

style.scss
.wrap > li:first-of-type,
.wrap > li:last-of-type {
   margin-bottom: 20px;
}

最初と最後以外

style.scss
.wrap > li:nth-child(n+2):nth-last-child(n+2)  {
   margin-bottom: 20px;
}

最後の要素以外に擬似要素

style.scss
div > span:not(:last-child):after{
  content:",";
}

aタグの_blankだけにcssを当てる

style.scss
a[target="_blank"] {
    background:#0099FF;
    color:#FFFFFF;
}

参考リンク

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3