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?

「ファイルを選択」ボタンが装飾できない理由とよくある解決策

Posted at

CSSを学んでいるみなさんへ。

フォームをCSSで装飾する際「なぜか装飾ができない」という箇所がありませんか。
代表的なのは「ファイルを選択(Choose File)」ボタンです。



開発モードでボタンを触ってみると、#file-upload-buttonとIDが設定されていることがわかります。
しかし、#file-upload-button{}で記述しても、反映されないんですよね。

なんで装飾できないの?

結論から言うと、input[type="file"]は普通のボタンと違って、
ブラウザ側で強制的にスタイルが適用される特別な要素だからです。

セキュリティの理由で、input[type="file"]はブラウザ側が制御しています。

だから、普通に #file-upload-button {} でIDを指定しても、CSSがほとんど反映されないんです。

じゃあどうすればいいの?

よく使われている具体的な解決策をg紹介します。デザインは例です。

index.html
<label for="file-upload-button" class="custom-file-upload">
  ファイルを選択
</label>
<input id="file-upload-button" type="file" style="display: none;">
style.css
.custom-file-upload {
  cursor: pointer; /* labelをボタン化する*/
  display: inline-block;
  padding: 10px 20px;
  border-radius: 5px;
  background-color: #ccc;
  color: #333;
  font-weight: bold;
  transition: .3s;
}

.custom-file-upload:hover {
  background-color: #999;
}

ここがポイント!

  • 本物のinput[type="file"]は非表示
  • かわりにカスタムボタン(label)を表示させる
  • ボタンをクリックするとちゃんとファイル選択ダイアログが開く!

まとめ

  • 「ファイルを選択」ボタンは、CSSで見た目を直接変えられない
  • なので、label+非表示で「見た目だけカスタマイズ」するのが王道

以上でした!
誰かのお役に立てていますように~。

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?