CSS 物件定位網頁置中版面設計
網頁版面的文章介紹位置居中,讓版面左右 A1, A2 留出一些邊界看起來比較舒適。瀏覽按鈕區 Navigation 在左側浮動位置的向上偏移 B 重疊顯示。版面 div.element-center 裡面的元素,<h1> title、<strong> 的數字樣式及 <div> Box 的位置居中(重點描述)。

title3
Box
HTML
<div class="element-center"> <h1>title<strong>3</strong></h1> <div>Box</div> </div>
CSS
div.element-center { margin:20px 0px; padding:5px 10px; width:790px; height:150px; border:1px solid #c8cfe1; } div.element-center h1 { margin:10px 0px; padding:3px 10px; font-size:24px; color:#4d5363; background-color:#e4e5e7; } div.element-center h1 strong { margin:-10px 0px 0px 0px;/* 負數則垂直位置 -10px 往上移動 */ padding:4px 10px; font-size:12px; color:#fff; background-color:#4d5363; float:right; } div.element-center div { margin:0 auto;/* 元素水平置中 */ width:250px; height:80px; font-size:28px; line-height:80px;/* 垂直置中值與 height 相同 */ color:#4aa83b; background-color:#cacbd0; text-align:center; }
網頁版面主要區塊
網頁版面主要區塊分為五個、Top、Header、Navigation、Content 及下方 Footer。
其中 Navigation 瀏覽按鈕區塊、Content 文章介紹區塊包裝在 wrapper 區塊之內讓位置居中於瀏覽器的視窗中,
並且 Content 區塊的 CSS 設置 overflow: hidden 元素超出矩形格時或說重疊顯示的方法可參考 overflow 的當內容超出元素的矩框時要如何展現有顯示結果的比較。
網頁下方 Footer 配合頁面的高度設置、可以不拘內容的高度而位置於視窗下方。
HTML
<!DOCTYPE html> <html lang="zh-TW"> <head> <title>網頁版面設計</title> </head> <body> <div class="topNav"> Top <!--(1)--> </div> <div class="header"> Header <!--(2)--> </div> <div class="wrapper"> <div class="leftNav"> Navigation <!--(3)--> </div> <div class="content"> <!--(4 Content)--> <h1>title<strong>3</strong></h1> <br /> <div class="box-c">Box</div> </div> </div> <div class="footer"> Footer <!--(5)--> </div> </body> </html>
CSS
html{height:100%;} /* 頁面的高度設置 */* html body{height:100%;}body{ margin:0; padding:0; min-height:100%; /* 瀏覽器的視窗大小改變時顯示處理 */ position:relative; /* 相對的位置 */ } div.topNav{ background-color:#4d5363; } div.header{ background-color:#a6a9b1; height:100px; /* 高度的設置 */ }
Wrapper
div.wrapper{ margin:0 5%; /* 左右邊距離 5% 版面置中 */ } div.content{ overflow: hidden; /* 元素超出矩形格時或說重疊 */ } div.leftNav{ width:200px; max-width:36%; /* 瀏覽按鈕區域的寬度 */ margin:20px 20px 0px 10px; float:left; /* 元素設為在左側浮動 */ }
Footer
div.footer{ clear:both; width:100%; position:absolute; bottom:0; /* 設置位置於下方 */ height:80px; background-color:#4d5363; }
版面內元素居中範例
以上概略的網頁版面以盡量簡化細節來描述結構 Html 範例請由此 查看網頁版面範例。
使用 Flexbox 伸縮盒配置居中的區塊容器
div.center-block { margin:10px; height:100px; border:1px solid #d3d6d9; transition: all .15s linear; } div.center-block { display:flex; align-items:center; justify-content:center; } div.center-block:hover { height:120px; } div.center-block div { width:300px; height:50px; line-height:50px; font-size:24px; text-align:center; background-color:#f3dc80; transition: all .15s linear; } div.center-block div:hover { height:80px; line-height:80px; cursor:pointer; }
簡單居中範例請由此 查看伸縮盒網頁版面範例。