编码规范、垂直居中、伪类和伪元素系统讲解

2017-10-07  本文已影响0人  曾祥辉

1.代码编码规范

2.常见的垂直居中实现方式

  1. 上下padding相等
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<style>
  .content {
    border: 1px solid black;
    padding: 30px 0;
    text-align: center;
  }  
</style>  
<body>
  <div class="content">
    <p>多行文字垂直居中</p>
    <p>多行文字垂直居中</p>
  </div>
</body>
</html>
  1. 绝对定位-负margin
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    .middle {
       height: 50px;
       width: 50px;
       position: absolute;
       top: 50%;
       margin-top: -25px;
       /*transform: translate(-50%, -50%)*//*CSS3*/
       border: 1px solid red;
    }
  </style>
</head>
<body>
  <div class="middle"></div>
</body>
</html>
  1. 行高与高度相等
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    .wrap {
      height: 100px;
      line-height: 100px;
      background-color: #ccc;
    }
  </style>
</head>
<body>
  <div class="wrap">
    <p>文字垂直居中</p>
  </div>
</body>
</html>
  1. 行内元素或表格设置vertical-align: middle属性
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    .wrap {
      height: 100px;
      display: table-cell;
      background-color: #ccc;
      vertical-align: middle;
    }
  </style>
</head>
<body>
  <div class="wrap">
    <p>文字垂直居中</p>
  </div>
</body>
</html>
  1. 伪元素和 inline-block / vertical-align
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    .wrap {
      height: 500px;
      background-color: #ccc;
    }
    .wrap p {
      vertical-align: middle;
    }
    .middle:before {
      content: "";
      display: inline-block;
      height: 100%;
      vertical-align: middle;
    }
  </style>
</head>
<body>
  <div class="wrap middle">
    <span>文字垂直居中</span>
  </div>
</body>
</html>

3.demo

上一篇下一篇

猜你喜欢

热点阅读