講清楚基礎系列——css佈局

兩列或三列布局

  • 使用flex
  • float
  • 左右position:absolute,中間margin-left,margin-right
聖盃和雙飛翼佈局,都是爲了實現一個兩側寬度固定,中間寬度自適應的三欄佈局。
<!-- 
聖盃佈局:
column左浮動
center寬度100%,不然會致使高度坍塌
left使用負外邊距margin-left:-100%,而後使用相對定位定位到最左邊
right直接使用負邊距居右
-->
<header id="header">header</header>
<main id="container">
  <div id="center" class="column">center</div>
  <div id="left" class="column">left</div>
  <div id="right" class="column">right</div>
</main>
<footer id="footer">footer</footer>

<!--  雙飛翼-->
<header id="header">header</header>
<main id="container" class="column">
  <div id="center">center</div>
</main>
<aside id="left" class="column">left</aside>
<aside id="right" class="column">right</aside>
<footer id="footer"></footer>

垂直水平居中

  • 水平居中text-align:center和塊級元素的margin:0 auto;
  • table方案,(IE8+)
<style>
.table{
    display:table;
}
.cell{
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}
</style>
<div class="table">
    <div class="cell">
        <img src="http://p0.qhimg.com/t01c430356016e16a2c.png" alt="" />
    </div>
</div>
  • absolute+margin:auto方案,兼容主流的瀏覽器;可是須要定義父容器的高度,不然子元素絕對定位會致使父元素的坍塌。
.absolute-aligned {
    position: relative;
    min-height: 500px;
    background: hsl(200, 100%, 97%);
}
.absolute-aligned img {
    margin: auto;
    position: absolute;
    top: 0; left: 0;
    bottom: 0; right: 0;
}
  • absolute+translate,(IE9+),一樣須要設置父元素的高度
.center {
    background: hsl(180, 100%, 97%);
    position: relative;
    min-height: 500px;
}
.center img {
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
    width: 30%; 
}
  • Flexbox方案
.center { 
    background: hsl(240, 100%, 97%);
    display: flex;
    justify-content: center;
    align-items: center;
}
  • calc方案,IE9+,更適合子元素寬高固定的狀況
// 50%是父元素的中心點,減去圖片寬度和高度的一半從而達到定位效果
.calc {
  background-color: hsl(300, 100%, 90%);
  min-height: 350px;
  position: relative;
}

.calc img {
  width: 100px;
  height: 100px;
  position: absolute;
  left: calc(50% - 50px);
  top: calc(50% - 50px);
}
相關文章
相關標籤/搜索