LoginSignup
11
7

More than 3 years have passed since last update.

【初心者でもわかる】hover時のCSSをhtmlのタグに直接書く方法

Posted at

どうも7noteです。hover時にだけCSSを当てる方法。

CSSは.cssファイルに書くか、<style></style>の中に書くのが一般的ですが、HTMLのタグの中に書くことも可能です。

index.html
<!-- HTMLのタグに直接CSSを書く方法 -->
<div style="background:#CCF;">てすとてすと</div>

しかし、この方法には欠点があり:hoverなどの疑似セレクタがついた時のCSSを指定することができません。
(※ほかにも管理がしにくいなどの欠点もあります。)

ですが、onMouseOutとonMouseOverの属性を使うことで:hoverと同じようにCSSを反映することができます!

hover時のCSSをhtmlのタグに直接書く方法

index.html
<div style="background:#CCF;" onMouseOut="this.style.background='#CCF';" onMouseOver="this.style.background='#EEF'">てすとてすと</div>

結果
sample.gif

このようにボタンの上にカーソルが乗った時に色が変わります。

文字色も変えたい!複数処理をするときはセミコロン(;)で繋ぐ。

index.html
<div style="background:#CCF;" onMouseOut="this.style.background='#CCF';this.style.color='#000';" onMouseOver="this.style.background='#EEF';this.style.color='#F00';">てすとてすと</div>

結果
sample02.gif

またjavascriptで関数を動かすこともできるので以下のような書き方でも同じ処理をすることが可能です。

index.html
<div id="hover-btn" style="background:#CCF;" onMouseOut="omOut();" onMouseOver="omOver();">てすとてすと</div>

<script>
function omOut(){
  document.getElementById('hover-btn').style.background='#CCF';
  document.getElementById('hover-btn').style.color='#000';
}
function omOver(){
  document.getElementById('hover-btn').style.background='#EEF';
  document.getElementById('hover-btn').style.color='#F00';
}
</script>

同じ結果になりました。
sample02.gif

まとめ

htmlだけやjsを使って:hoverの代わりの処理を入れることはできますが、可能なのであればやはりCSSファイルでちゃんと:hoverとかける方が作りやすいし管理もしやすいですね。
でもどうしてもhtmlのタグしかかけないときに使える技です!

困ったときに使えるTipsでした。

参考:https://teratail.com/questions/151338

おそまつ!

~ Qiitaで毎日投稿中!! ~
【初心者向け】WEB制作のちょいテク詰め合わせ

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