天天看點

08-DIV+CSS-塊元素和行内元素1. 概念2. 差別3. 互相轉化

塊元素和行内元素

1. 概念

 - 行内元素(inline element), 又叫内聯元素

   内聯元素隻能容納文本或者其他内聯元素,

   即, 值棧内容寬度,預設不換行

   常見内聯元素<span><a>

 - 塊元素(block element)

   塊元素一般都從新行開,可以容納文本 内聯元素 塊元素,

   即, 塊元素中内容即使不滿一行,塊元素也要占整行,要換行.

   常見塊元素 <div> <p>

2. 差別

 1)寬度

    行内元素隻占内容的寬度,

    塊元素内容不管内容多少都要占全行

 2)内容

    行内元素隻能容納文本和其他行内元素

    塊元素可以容納 文本 行内元素 塊元素

 3)有效性

    一些css屬性對行内元素不生效,

    如 margin left right width height等

    建議盡可能使用塊元素.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <title>css1.html</title>
      <meta http-equiv="keywords" content="value1,value2,...">
      <meta http-equiv="content-type" content="text/html;charset=UTF-8">

    <style type="text/css">
      
      .spanCls {
        background-color: pink;
        border: 1px solid red;
      }

      .divCls {
        background-color: gray;
        border: 2px solid red;
      }
     
      .pCls {
        background-color: green;
        border: 3px solid red;
      }

      #innerDiv {
        background-color: black;
        width: 200px;
        color: white;
      }

    </style>

  </head>
  <body>
    
    <span class="spanCls">我是span1</span>
    <span class="spanCls">我是span2</span>
    <span class="spanCls">我是span3</span>
    
    <br/><hr/><br/>
    
    <div class="divCls">我是div1</div>
    <div class="divCls">我是div2</div>
    <div class="divCls">我是div3</div>

    <br/><hr/><br/>
    
    <p class="pCls">我是p1</p>
    <p class="pCls">我是p2</p>
    <p class="pCls">我是p3</p>

    <br/><hr/><br/>
    
    <div class="divCls">
        outer div
        <div id="innerDiv">inner div</div>
    </div>
    

  </body>
</html>
           

3. 互相轉化

 1) 文法

    display:inline  ==> 轉為行内元素

    display:block   ==> 轉為塊元素

    注: 僅樣式的轉換

 2) 舉例    

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
      <title>css2.html</title>
      <meta http-equiv="keywords" content="value1,value2,...">
      <meta http-equiv="content-type" content="text/html;charset=UTF-8">

    <style type="text/css">
      
     div {
        background-color: green;
        display: inline;
     }

     span {
        background-color: gray;
        display: block;
     }

    </style>

  </head>
  <body>
    
    <div>其實, 我是div</div>

    <hr/>

    <span>其實, 我是span</span>



  </body>
</html>