css都有哪些布局方式?

布局是CSS中一个很重要的部分,也是最不好处理的一部分,其他诸如字体大小、颜色等等都是很容易的。总结一下使用过的CSS常用布局,包括水平居中、垂直居中、单列布局、多列布局等,以及flex布局。

css布局方式介绍:

1、水平居中:

内联元素水平居中

利用 text-align: center 可以实现在块级元素内部的内联元素水平居中。此方法对内联元素(inline), 内联块(inline-block), 内联表(inline-table), inline-flex元素水平居中都有效。
核心代码:

.center-text {
  text-align: center;
}

块级元素水平居中

通过把固定宽度块级元素的margin-left和margin-right设成auto,就可以使块级元素水平居中。
核心代码:

.center-block {
  margin: 0 auto;
}

多块级元素水平居中

利用inline-block

如果一行中有两个或两个以上的块级元素,通过设置块级元素的显示类型为inline-block和父容器的text-align属性从而使多块级元素水平居中。
核心代码:

.container {
    text-align: center;
}
.inline-block {
    display: inline-block;
}

2、垂直居中

单行内联(inline-)元素垂直居中

通过设置内联元素的高度(height)和行高(line-height)相等,从而使元素垂直居中。
核心代码:

#v-box {
    height: 120px;
    line-height: 120px;
}

多行元素垂直居中

利用表布局(table)

利用表布局的vertical-align: middle可以实现子元素的垂直居中。
核心代码:

.center-table {
    display: table;
}
.v-cell {
    display: table-cell;
    vertical-align: middle;
}

3、利用flex布局(flex)

利用flex布局实现垂直居中,其中flex-direction: column定义主轴方向为纵向。因为flex布局是CSS3中定义,在较老的浏览器存在兼容性问题。
核心代码:

.center-flex {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

4、单列布局

主要有两种:
- header, content, footer宽度相同,有一个max-width
- header和footer占满浏览器100%宽度,content有一个max-width

第一种

<header style="background-color: red; width: 600px; margin: 0 auto;">头部</header>
<main style="background-color: green; width: 600px; margin: 0 auto;">内容</main>
<footer style="background-color: yellow; width: 600px; margin: 0 auto;">尾部</footer>

第二种:

<header style="background-color: red;">头部</header>
<main style="background-color: green; width: 600px; margin: 0 auto;">内容</main>
<footer style="background-color: yellow;">尾部</footer>

5、两列布局

float + margin

用float将边栏与主要内容拉到一行,然后设置主要内容的margin。

<main style="background-color: red;">
  <aside style="background-color: yellow; float: left; width: 50px;">边栏</aside>
  <section style="background-color: green; margin-left: 50px;">主要内容</section>
</main>

以上就是css都有哪些布局方式?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑