CSSだけでできる!div要素の内側にボーダーを表示する方法
div要素の内側にボーダーを配置する方法
<div class="container">
<h1>タイトル</h1>
<p>本文</p>
</div>
CSS
.container {
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 20px;
}
.container h1 {
font-size: 18px;
margin-top: 0;
}
.container p {
margin-bottom: 0;
}
上記のように、div
要素にborder
プロパティを指定することで、その要素の外側にボーダーを表示することができます。
しかし、border
プロパティは要素の外側にのみ適用されます。そのため、div
要素の内側にボーダーを表示するには、別の方法が必要です。
box-shadow
プロパティは、要素の周りに影を表示するプロパティです。このプロパティを使って、div
要素の内側に影を表示することで、ボーダーのように見せることができます。
.container {
width: 300px;
height: 200px;
box-shadow: inset 0 0 1px #ccc;
}
上記のように、box-shadow
プロパティにinset
キーワードを指定することで、影を要素の内側に表示することができます。
0 0 1px #ccc
の部分は、影の位置、ぼかし具合、色を指定しています。
0 0
:影の位置を要素の中央に設定1px
:影のぼかし具合を1pxに設定#ccc
:影の色をグレーに設定
.container {
width: 300px;
height: 200px;
border-image: url(border.png) 1 1 repeat;
}
上記のように、border-image
プロパティに画像のURLを指定することで、その画像をボーダーとして表示することができます。
1 1 repeat
の部分は、画像の幅、高さ、繰り返し方を指定しています。
1
:画像の幅と高さを1pxに設定repeat
:画像を横方向と縦方向に繰り返し表示
pseudo-element
は、要素の後に追加される擬似要素です。この要素を使って、div
要素の内側にボーダーを表示することができます。
HTML
<div class="container">
<h1>タイトル</h1>
<p>本文</p>
</div>
.container {
width: 300px;
height: 200px;
position: relative;
}
.container::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border: 1px solid #ccc;
}
上記のように、::before
疑似要素を使って、div
要素の内側にボーダーを表示することができます。
content: "";
の部分は、疑似要素の内容を空に設定しています。
position: absolute;
の部分は、疑似要素を絶対配置に設定しています。
top: 0; left: 0; right: 0; bottom: 0;
の部分は、疑似要素をdiv
要素の全体に配置しています。
div
要素の内側にボーダーを表示するには、いくつかの方法があります。それぞれの方法にはメリットとデメリットがあるので、目的に合った方法を選択する必要があります。
box-shadow
プロパティ:簡単に使えるが、ぼかし効果があるため、シャープなボーダーを表示できないborder-image
プロパティ:シャープなボーダーを表示できるが、画像を用意する必要があるpseudo-element
box-shadowプロパティを使う
<div class="container">
<h1>タイトル</h1>
<p>本文</p>
</div>
.container {
width: 300px;
height: 200px;
box-shadow: inset 0 0 1px #ccc;
}
border-imageプロパティを使う
<div class="container">
<h1>タイトル</h1>
<p>本文</p>
</div>
.container {
width: 300px;
height: 200px;
border-image: url(border.png) 1 1 repeat;
}
pseudo-elementを使う
<div class="container">
<h1>タイトル</h1>
<p>本文</p>
</div>
.container {
width: 300px;
height: 200px;
position: relative;
}
.container::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border: 1px solid #ccc;
}
各方法のメリットとデメリット
box-shadowプロパティ
- 簡単
デメリット
- ぼかし効果があるため、シャープなボーダーを表示できない
border-imageプロパティ
- シャープなボーダーを表示できる
- 画像を用意する必要がある
- コードが複雑になる
pseudo-element
:シャープなボーダーを表示できる
div要素の内側にボーダーを表示する他の方法
.container {
width: 300px;
height: 200px;
outline: 1px solid #ccc;
outline-offset: -1px;
}
outline-offset
プロパティは、アウトラインの位置を調整するプロパティです。上記のように、outline-offset
プロパティに負の値を指定することで、アウトラインを要素の内側に表示することができます。
.container {
width: 300px;
height: 200px;
border: 1px solid #ccc;
border-style: inset;
}
inset
キーワードを指定することで、二重線を要素の内側に表示することができます。
.container {
width: 300px;
height: 200px;
background-image: url(border.png);
}
html css border