2017年12月7日 星期四

HTML CSS (5) - 網頁排版

5-1 關於如何將兩個元素並排:

https://stackoverflow.com/questions/5759554/displayinline-resets-height-and-width/5759565#5759565
根據這篇可知道,inline attribute並沒有長寬,因此如果要使兩個元素有inline的效果,需要使用floatinline-block.

浮動效果float:會根據元素大小並排。若寬度比瀏覽器寬度長,則下一個元素會被推到下一層
float:left;往左靠
float:right; 往右靠

.box{
  width: 200px;
  height: 50px;
  background: black;
  float:left;
}
.box2{
  width: 200px;
  height: 50px;
 background: pink;
  float:left;
}



兩個長方形200+200比瀏覽器寬度小,會並排











若將.box寬度設為2000px,則會變下圖:












解決方法:
可使用wrap包住兩個box,並給wrap寬度,使得兩個box可以有最大寬度限制
注意使用float:left要寫width!

.wrap{
  margin:0 auto;
  width:3000px;
}
.box{
  width: 2000px;
  height: 50px;
  background: black;
  float:left;
}
.box2{
  width: 200px;
  height: 50px;
  background: pink;
  float:left;
}

則可併排顯示





註: .若兩個box的寬度超過3000則box2會到下一行
可使用float設計三欄式排版


5-2 float並排問題:

假設現有四個區塊被包在wrap裡
<body>
    <div class="wrap">
     <div class="header"></div>
        <div class="content"></div>
        <div class="menu"></div>
        <div class="footer"></div>
    </div>
</body>
將wrap寬度固定為1000,預期footer會從menu後面開始排
.wrap{
 margin:auto;
 width:1000px;
}
.header{
 height: 50px;
 background: red;
}
.content{
 width: 200px;
 height: 100px;
 background: black;
 float:left;
}
.menu{
 width: 800px;
 height: 100px;
 background: pink;
 float:right;
}
.footer{
 height: 300px;
 background: gray;
}
結果:灰色區塊顯示區域只有200
float的並排並不會佔住沒有float效果的空間,如下圖:


解決方法:最後一個float元素(menu)下加上清除浮動的效果

<body>
    <div class="wrap">
     <div class="header"></div>
        <div class="content"></div>
        <div class="menu"></div>
        <div class="clearfix"></div>
        <div class="footer"></div>
    </div>
</body>
 css: clearfix需加上clear:both;

.clearfix{
 clear:both;
}

5-3 文字內排版及上下margin

中間內容若需要可作延伸,則不能限制外圍高度
限制黑色box高度為50px,裡面放字時:






















黑色box高度移除時:
















5-4 選單橫式排版

  • ul li橫式排版可使用
    1. display inline
    2. float:left
  • 文字垂直置中方式
    1. 設定line-height:高度 (與block內高度相同) 注意只能放一行
    2. 可設定padding top,padding bottom
  • 文字除去下底線 text-decoration: none;
  • 文字水平置中方式 text-align: center;
  • 避免float依序做排序
    1. 設定block高度
    2. 使用clear:both

5-5 選單橫式排版

  1. 新增一圖片
  2. 新增ul li,ul的class設定float:right
  3. 上下左右根據padding及margin做調整








完成項目:

沒有留言:

張貼留言