概要
body内にheader要素を置き、全体をスクロールしたときにheaderのみ固定されて動かないようにしたいとき。
CSSで以下を設定する。
position: fixedtop: 0box-sizing: border-boxwidth: 100%
HTML
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="header_fix.css"> <title>Fix Header</title> </head> <body> <header> <h1>吾輩は猫である</h1> </header> <main> <p> 吾輩は猫である。名前はまだ無い。 </p> ・・・・・・ </main> </body> </html> |
CSS
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
body { margin: 0; } header { position: fixed; top: 0; box-sizing: border-box; width: 100%; height: 6em; border: solid 2px blue; } main { margin-top: 6em; } |
body要素
margin: 0を指定する
header要素
position: fixed指定でheader要素を固定するheader要素の幅がコンテンツの文字の長さまで短くなってしまう
width: 100%指定でheaderの親要素bodyの幅まで広げる- ただしCSSのボックスモデルでは
widthとheightはコンテンツの幅と高さなので、右端がはみ出てしまう
- ただしCSSのボックスモデルでは
box-sizing: border-box指定でheaderのボーダーがbodyの幅に合うようにする- top: 0指定で
メインコンテンツ
margin-topを指定して、メインコンテンツの先頭がheaderとラップしないようにする