讲清楚基础系列css布局

9次阅读

共计 1671 个字符,预计需要花费 5 分钟才能阅读完成。

两列或三列布局

  • 使用 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);
}

正文完
 0