18.12.1 課題内容
指示書を完成させる(headerをスクロールしても固定されるようにする)
- 与えられている雛形
sample.html
<!DOCTYPE html>
<html lang="en" class="">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="sample.css">
</head>
<body>
<div class="wrapper">
<header>
</header>
<div class="contents">
<div class="left-content">
</div>
<div class="right-content">
</div>
<div class="bottom-content">
</div>
</div>
<footer>
</footer>
</div>
</body>
</html>
sample.css
html, body{
height: 100%;
margin: 0;
padding: 0;
}
.wrapper{
height: 100%;
}
header{
background-color: #333;
height: 70px;
}
.contents{
width: 960px;
background-color: #eee;
margin: 0 auto;
}
.left-content{
background-color: red;
width: 700px;
height: 400px;
}
.right-content{
background-color: yellow;
width: 260px;
height: 300px;
}
.bottom-content{
background-color: green;
height: 250px;
}
footer{
height: 60px;
background-color: #333;
}
1.body部分の黄を赤の左に配置したい!
まず、以下のようにcssを指定すると
sample.css
.left-content /*赤*/{
background-color: red;
width: 700px;
height: 400px;
float:left; /*左寄せにしたいので*/
}
.right-content /*黄*/{
background-color: yellow;
width: 260px;
height: 300px;
}
.bottom-content/*緑*/{
background-color: green;
height: 250px;
clear:both; /*左寄せを解除*/
}
.right-content(黄)が消えました・・・正しくは赤の下に潜り込んでいました
この問題を解決するには
.right-contentにもfloat:left;をかける
sample.css
.left-content /*赤*/{
background-color: red;
width: 700px;
height: 400px;
float:left; /*左寄せにしたいので*/
}
.right-content /*黄*/{
background-color: yellow;
width: 260px;
height: 300px;
float:left;/*追加部分*/
}
.bottom-content/*緑*/{
background-color: green;
height: 250px;
clear:both; /*左寄せを解除*/
}
2.headerを固定する
固定するために下記のコードを追記しました
sample.css
header{
background-color: #333;
width:100%;
height: 70px;
/*以下3行追記部分*/
position:fixed;
top:0;
z-index:100;
}
するとbodyの上部分がheaderと重なってしまいました(headerの高さ分ずれてしまっています)
headerの高さ(70px)分padding-topでずらすとうまくいきました
sample.css
.contents{
width: 960px;
background-color: #eee;
margin:0 auto;
padding-top: 70px;/*追記部分*/
}