CSS 垂直居中

来源:互联网 发布:国动网络通信集团网站 编辑:程序博客网 时间:2024/06/04 20:39

Css 垂直居中主要有以下几种方法:

 方法一:如果是行内元素,可通过上下内边距填充相同距离:如

<html>

body {
  background: #f06d06;
  font-size: 80%;
}


main {
  background: white;
  margin: 20px 0;
  padding: 50px;
}


main a {
  background: black;
  color: white;
  padding: 40px 30px;
  text-decoration: none;
}

<main>
  <a href="#0">We're</a>
  <a href="#0">Centered</a>
  <a href="#0">Bits of</a>
  <a href="#0">Text</a>
</main>

2、方法二:将行高height与行间距line-height设置相同值

body {
  background: #f06d06;
  font-size: 80%;
}


main {
  background: white;
  margin: 20px 0;
  padding: 40px;
}


main div {
  background: black;
  color: white;
  height: 100px;
  line-height: 100px;
  padding: 20px;
  width: 50%;
  white-space: nowrap;
}

<main>
  <div>
    I'm a centered line.
  </div>
</main>

方法三:若文本是多行文本,在css里面有个display:table-cell;属性值可以让元素渲染为表格单元格,就可以轻松实行让子元素水平垂直居中了,自己试下

.center-table {
  display: table;
  height: 250px;
  background: white;
  width: 240px;
  margin: 20px;
}
.center-table p {
  display: table-cell;
  margin: 0;
  background: black;
  color: white;
  padding: 20px;
  border: 10px solid white;
  vertical-align: middle;
}

方法四:利用vertical-align:middle
这个方法目前是我的最爱,因为下面介绍的兼容性不是很好
这个是利用一个没有宽度b标签来实现水平垂直居中
<style>
.wrap {width:300px; height:300px; text-align:center; background:rgba(0,0,0,0.5);}
.vamb {display:inline-block; width:0px; height:100%; vertical-align:middle;}
.test {background:red; display:inline-block;}
</style>

<div class="wrap">
<b class="vamb"></b>
<div class="test">
CSS吧<br>
来个宽度大点的试试
</div>
</div>

方法五:弹性盒模型
弹性盒模型就是flex,css3新增布局方式,超级好用,谁用谁知道,推荐大家都学习一番。
这个方法我在手机端都很喜欢用,相对爽啊 呵呵。同样比较遗憾的是低版本IE不支持,不过手机端是没有问题的,使用旧版方法display:box;
<style>
*{margin:0px; padding:0px;}
.flex {display:-webkit-box; display:-ms-flex; display:-webkit-flex; display:flex;}
.flex-hc {-webkit-box-pack:center; -ms-justify-content:center; -webkit-justify-content:center; justify-content:center;}
.flex-vc {-webkit-box-align:center; -ms-align-items:center; -webkit-align-items:center; align-items:center;}
.wrap {position:fixed; width:100%; height:100%; background:rgba(0,0,0,0.5); left:0px; top:0px;}
</style>

<div class="wrap flex flex-hc flex-vc">
<div class="test">
<img src="girl/tpl_7.jpg" width="200" >
</div>
</div>


0 0
原创粉丝点击