【CSS】 Floatを使ったレイアウト
Floatを使ったレイアウトを使うことで、横並びのページを作ることができます。
Floatを使い場合は、floatさせた要素が他のスタイルに潜り込まないように、overflow:hidden;(はみ出した要素を隠す)を設定するのが一般的です。
2カラムレイアウト
2カラムレイアウトを作る際には、floatさせる要素をwrapperで囲み、overflow:hidden; をかけます。
ソース
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>ページタイトル</title> <style> html, body, div, h1, h2, p{ padding:0; margin:0; line-height:1.0; } #container { width: 760px; margin: 10px auto; } #header { height: 100px; background: #DDDDDD; margin-bottom: 10px; } #wrapper{ overflow: hidden; margin-bottom: 10px; } #content{ width: 500px; height: 200px; float: right; background: #C7D5EE; } #sidebar{ width: 250px; height:200px; float: left; background: #FACFB8; } #footer{ height: 100px; background: #DDDDDD; } </style> </head> <body> <div id="container"> <div id="header"> </div> <div id="wrapper"> <div id="content"> </div> <div id="sidebar"> </div> </div><!--/#wrapper--> <div id="footer"> </div> </div><!--/#container--> </body> </html>
3カラムレイアウト
3カラムレイアウトをつくる時の考え方としては、2カラムを二つ用意して、2番目のレイアウトのfooterだけfloatを解除させます。
このとき、2番目のカラムには、clear:both; をfooterで使うため、overflow:hidden; が必要ありません。
footerがないときでも同じような考えで3カラムにすることが可能です。
イメージとしては上の画像のように、CSSでレイアウトを作ります。
ソース
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>ページタイトル</title> <style> html, body, div, h1, h2, p{ padding:0; margin:0; line-height:1.0; } #container { width: 760px; margin: 10px auto; } #header { height: 100px; background: #DDDDDD; margin-bottom: 10px; } #wrapper{ overflow: hidden; float: left; } #content{ width: 500px; height: 200px; float: right; background: #C7D5EE; margin-bottom: 10px; } #sidebar1{ width: 120px; height: 200px; float: left; background: #FACFB8; margin:0 10px 10px 0; } #sidebar2{ width: 120px; height: 200px; float: right; background: #E6C6EE; margin-bottom: 0 0 10px 10px; } #footer{ clear: both; height: 100px; background: #DDDDDD; } </style> </head> <body> <div id="container"> <div id="header"> </div> <div id="wrapper"> <div id="content"> </div> <div id="sidebar1"> </div> </div><!--/#wrapper--> <div id="sidebar2"> </div> <div id="footer"> </div> </div><!--/#container--> </body> </html>