前端常见基本布局

一、侧边栏布局

这种布局也是我们很常见的内容,就比如说,网站的个人中心,以及很多后台管理系统都是这样的(我们的运营后台)。

这种布局呢,主要是因为左边的sidebar宽度是固定的,右边的内容区会跟着屏幕的宽度的变化进行变化的。实现这样的布局的方式有很多,这里先讲三种:

1.1 第一种flex布局,代码如下:

        .container {
            display: flex;
            width: 100%;
            height: 100%;
            background: #ddd;
        }

        .aside {
            width: 200px;
            height: 100%;
            background: pink;
        }

        .main {
            width: 100%;
            height: 100%;
            flex: 1;
            background: skyblue;
        }

 

html 内容:

<div class="container">
  <div class="aside">aside</div>
  <div class="main">main</div>
</div>

 

这种方案有兼容问题在不考虑ie系列的,以及旧版的谷歌和火狐的前提下可以使用, 兼容写法可以参考: https://www.jianshu.com/p/49cdc1a0b69b

1.2 绝对定位

这种方式比较通用,兼容性相对来说比较好,很多情况下会使用这种方式来进行布局,代码如下:

.container {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding-left: 200px;
}
.aside {
  position: absolute;
  left: 0;
  top: 0;
  width: 200px;
  height: 100%;
  background: pink;
}
.main {
  position: relative;
  height: 100%;
  background: skyblue;
}

 

其中html代码不用发生变化。

1.3 float定位

这种布局在很多地方也都有用到,代码如下:

.container {
  position: relative;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.aside {
  position: relative;
  float: left;
  width: 200px;
  height: 100%;
  background: pink;
  z-index: 1;
}
.main {
  position: relative;
  height: 100%;
  background: skyblue;
  box-sizing: border-box;
  padding-left: 200px;
}

 

二、垂直居中布局

对于垂直居中,比较常见的一个使用就是弹框。对于垂直居中的实现方式也有多种, 这里我们讲4种。

2.1 绝对定位+margin

首先来谈一下固定高度的垂直居中的实现方法,这个最常用的方法就是绝对定位加margin来进行实现的。如下

css

.container {
  position: relative;
  width: 100%;
  height: 100%;
}
.main {
  position: absolute;
  left: 50%;
  top: 50%;
  display: block;
  width: 200px;
  height: 200px;
  background: pink;
  margin-top: -100px;
  margin-left: -100px;
}

 

html

<div class="container">
  <div class="main">main</div>
</div>

 

很多的弹框插件都是基于这个来进行实现的。

2.2 绝对定位 + transform

对于这种方案,一般常用于不确定内容的宽高的情况下使用,而且这种方案中使用的css3的属性,所以这种方案的经常使用在在移动端。在移动端比如说很多活动的弹框啥的都是可以使用这个方案来进行实现。

代码如下:

.container {
  position: relative;
  width: 100%;
  height: 100%;
}
.main {
  position: absolute;
  left: 50%;
  top: 50%;
  display: block;
  width: 200px;
  height: 200px;
  background: pink;
  transform: translateX(-50%) translateY(-50%);
}

 

2.3 使用flex进行实现

这种方案需要知道内容的宽高的情况下进行实现的(兼容问题如1.1)

代码如下:

.container {
  position: relative;
  display: flex;
  width: 100%;
  height: 100%;
  justify-content: center;
  align-items: center;
}
.main {
  display: block;
  width: 200px;
  height: 200px;
  background: pink;
}

 

2.4 使用line-height

这种方案其实使用的不是很多,而且需要知道外围的具体高度

代码如下:

.container {
  display: block;
  width: 100%;
  height: 600px;
  line-height: 600px;
  text-align: center;
  background: #ddd;
}

 

posted @ 2017-03-22 11:03  yuxiaoliu  阅读(217)  评论(0)    收藏  举报