知っておきたい! インライン CSS で 'a:hover' を記述する3つの方法
インライン CSS で 'a:hover' を記述するには、以下の2つの方法があります。
style 属性
<a href="https://www.example.com/" style="color: red; text-decoration: underline;">リンク</a>
上記の例では、style
属性を使用して、color
プロパティと text-decoration
プロパティを設定しています。
color: red;
は、マウスポインターがリンクの上に置かれたときに、リンクの色を赤に変更します。text-decoration: underline;
は、マウスポインターがリンクの上に置かれたときに、リンクに下線を引きます。
onmouseover 属性と onmouseout 属性
<a href="https://www.example.com/" onmouseover="this.style.color='red'; this.style.textDecoration='underline';" onmouseout="this.style.color=''; this.style.textDecoration='';">リンク</a>
上記の例では、onmouseover
属性と onmouseout
属性を使用して、マウスポインターがリンクの上に入ったときと出たときのスタイルを設定しています。
onmouseover
属性は、マウスポインターがリンクの上に入ったときに、this.style.color='red'
とthis.style.textDecoration='underline'
を実行します。これは、リンクの色を赤に変更し、下線を引きます。
- スタイルがシンプル な場合は、
style
属性を使用するのが簡単です。 - スタイルが複雑 な場合は、
onmouseover
属性とonmouseout
属性を使用する方が柔軟性があります。
その他の注意事項
- インライン CSS は、スタイルの変更が少数の要素 に限定される場合にのみ使用することをおすすめします。
- スタイルシートを使用すると、スタイルをより効率的に管理 することができます。
HTML コード
<p>
<a href="https://www.example.com/">リンク1</a>
<a href="https://www.example.com/">リンク2</a>
<a href="https://www.example.com/">リンク3</a>
</p>
CSS コード
a:hover {
color: red;
text-decoration: underline;
}
実行結果
上記のコードを実行すると、ユーザーがマウスポインターをリンクの上に置いたときに、リンクの色が赤に変わり、下線が引かれます。
別の方法
<p>
<a href="https://www.example.com/" onmouseover="this.style.color='red'; this.style.textDecoration='underline';" onmouseout="this.style.color=''; this.style.textDecoration='';">リンク1</a>
<a href="https://www.example.com/" onmouseover="this.style.color='green'; this.style.textDecoration='underline';" onmouseout="this.style.color=''; this.style.textDecoration='';">リンク2</a>
<a href="https://www.example.com/" onmouseover="this.style.color='blue'; this.style.textDecoration='underline';" onmouseout="this.style.color=''; this.style.textDecoration='';">リンク3</a>
</p>
- リンクの色を変える
a:hover {
color: blue;
}
- リンクに下線を引く
a:hover {
text-decoration: underline;
}
a:hover {
background-color: yellow;
}
- リンクのフォントサイズを変える
a:hover {
font-size: 16px;
}
これらのサンプルコードを参考に、さまざまなスタイルを適用してみてください。
インライン CSS で 'a:hover' を記述するその他の方法
<head>
<style>
a:hover {
color: red;
text-decoration: underline;
}
</style>
</head>
<body>
<p>
<a href="https://www.example.com/">リンク</a>
</p>
</body>
上記の例では、style
タグを使用して、a:hover
のスタイルを定義しています。
JavaScript
<p>
<a href="https://www.example.com/" id="link">リンク</a>
</p>
<script>
const link = document.getElementById("link");
link.onmouseover = function() {
link.style.color = "red";
link.style.textDecoration = "underline";
};
link.onmouseout = function() {
link.style.color = "";
link.style.textDecoration = "";
};
</script>
- スタイルが複雑 な場合は、
style
タグまたは JavaScript を使用する方が柔軟性があります。
X
html css inline-styles