0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Formで必要事項が入力された時だけ押せるボタンのスタイルの当て方

Posted at

背景

Formを作成していると、最低限入力が必要な項目を全て満たさないと送信ボタンが押せない。
といった挙動を作りたくなることが多々あると思います。

  • disableの時
  • not disable
  • not disable & hover
  • not disable & active

のような状態に応じてスタイルを切り替えたい時ってあると思います。
scssでこれらのスタイルを当てようとした時にどのように記述すればいいかをメモとしてまとめます。

結論

&:not(:disable)を使おう

<button type="button" className={styles.saveButton} disable={isTitleEmpty}>
  保存
</button>

という要素があったとして、これに対し、

.saveButton {
  background-color: white;
  border: 2px solid lightskyblue;

  &:hover {
    color: white;
    background-color: lightskyblue;
  }

  &:active {
    color: white;
    background-color: cornflowerblue;
    border: none;
  }
}

というスタイルを当てていたとしたら、

.saveButton {
  background-color: white;
  border: 2px solid lightskyblue;

+ &:disable {
+   color: white;
+   background-color: #bc3838;
+   border: none;
+ }

- &:hover {
+ &:not(:disable):hover {
    color: white;
    background-color: lightskyblue;
  }

- &:active {
+ &:not(:disable):active {
    color: white;
    background-color: cornflowerblue;
    border: none;
  }
}

としてあげることで、
disableの時にはhover, activeのスタイルは当てずに、赤色表示のボタンとし、
isTitleEmptyfalseの条件になった時には、青色表示や、hover, activeのスタイルを当てることができるようになります。

まとめ

scssは色々な書き方があり、もっと可読性高くわかりやすいスタイルの当て方があるかもしれません。
ご存知の方はぜひコメント欄にてご教授ください。
今回初めて、:notを使うやり方を知れて、スタイルの当て方の幅が広がったような気がします。
今後も、スタイルの当て方勉強していきたいです。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?