clear属性

CSS入門

 
■概要
 
clear属性は、下記の3つの属性が使えます。

  • left:左側を消去
  • right:右側を消去
  • both:両方を消去
  •  
     
    ■例

    <html>
    <head>
    <style>
     .float-container{ width: 320px; border: 2px solid #09c; }
     .float-container img{ float: left; margin: 5px; padding: 5px; border: 2px solid #90C; }
    </style>
    </head>
    <body>
     <div class=”float-container”>
      <img src=”/images/planet.jpg”>
      <p>This is first line with floating image.</p>
      <p style=”clear: both”>This is second line with cleared property.</p>
     </div>
    </body>
    </html>

    出力結果

    This is first line with floating image.

    This is second line with cleared property.

     
    ■レイアウトでのclear
     
    clear属性は、floatをレイアウトで使う時に発生する色んな問題を解決するためにもよく使われます。
     
    ■例

    <style>
     .box-container{
      width: 400px;
      border: 3px solid #09c;
      background-color: #d7f5ff;
     }
     .box-container .box{
      width: 80px;
      height: 40px;
      border: 3px solid red;
      background-color: #ffe7d5;
     }
    </style>
    <div class=”box-container”>
     <div class=”box” style=”float: left”>ボックス1</div>
     <div class=”box” style=”float: right”>ボックス2</div>
    </div>
    <div>ボックスに表示する内容</div>

    出力結果

    ボックス1
    ボックス2
    ボックスに表示する内容

    ■例

    <div class=”box-container”>
     <div class=”box” style=”float: left”>ボックス1</div>
     <div class=”box” style=”float: right”>ボックス2</div>
     <div style=”clear: both”></div>
    </div>
    <div>ボックスの表示する内容</div>

    出力結果

    ボックス1
    ボックス2
    ボックスの表示する内容

     
    ■after仮想クラスセレクタとclear
     
    clearをするためには、floatが摘要された要素の後にclearタグを指定しないと行けません。
    この場合、仮想クラスセレクタを使えば簡単に解決できます。

    .clearfix:after{ content: “”; display: block; clear: both }

    しかし、after仮想セレクタはInternet Explorer8以下のバージョンでは動作しないですが、
    コンテナタグに*zoom: 1とオプションを付けると解決できます。
    ■例

    <style>
     .clearfix { *zoom: 1; }
     .clearfix:after { content: “”; display: block; clear: both; }
    </style>
    <div class=”box-container clearfix”>
     <div class=”box” style=”float: left”>ボックス1</div>
     <div class=”box” style=”float: right”>ボックス2</div>
    </div>
    <div>ボックスの下に表示する内容</div>

    出力結果

    ボックス1
    ボックス2
    ボックスの下に表示する内容

     
    floatとclearでレイアウトを構成する方法については
    レイアウトセクションで詳しく書きます。
     
     
     
     

    当サイトは広告を含めています。広告のクリックによる収益は全て当サイトの管理、維持、コンテンツ製作に使われます。

     

    Team ladybird
    タイトルとURLをコピーしました