zoukankan      html  css  js  c++  java
  • CSS系列-垂直居中

    <body>
      <div class="p">
        <div class="c">
          垂直居中
        </div>
      </div>
    </body>
    

    红色字体的是关键的实现 

    1. 使用flex(最优方案):

      父元素设置样式:

      .p {

        display: flex;

        align-items: center;

        justify-content: center;

      }

    2. 使用margin + relative + top + transform :

      父元素:

      .p {

        height: 100%;

        padding: 0;

        margin: 0;

      }

      子元素:

      .c {

        margin: 0 auto;

         300px;

        position: relative;

        top: 50%;

        transform: translateY(-50%);

      }

      注意:

        必须给子元素设置宽度;

        子元素必须是块元素;

    3. 使用margin + relative + top + margin-top:

      父元素:

      .p {

        height: 100%;

        padding: 0;

        margin: 0;

      }

      子元素:

      .c {

        margin: 0 auto;

         300px;

        height: 200px;

        position: relative;

        top: 50%;

        margin-top: 100px;

      }

      注意:

        必须给子元素设置宽度;

        必须给子元素设置高度;

        子元素必须是块元素

     

    4.  绝对定位+ 相对定位

      父元素相对定位 :

      .p{

        height: 200px;

        position: relative;

      }

      子元素: 

      .c {

        position: absolute;

        margin: auto;

        top: 0;

        bottom: 0;

        right: 0;

        left:0;

         50px;

        height: 50px;

        border: 1px solid red;

      }

      注意:

        必须给子元素设置宽度;

        必须给子元素设置高度;

     

    5. 使用伪类after + vertical-align:

      父元素 :

      .p{

         200px;

        height: 200px;

        text-align: center;

      }

      伪元素:

      .p::after {

        content: '',

        height: 100%;

        vertical-align: center;

        display: inline-block;

      }

      子元素: 

      .c {

        dislpay: inline-block;

        border: 1ps solid red;

      }

      注意:

        子元素是内联元素

      

  • 相关阅读:
    原型prototype
    this
    作用域、闭包、模块
    嵌入式面试资料
    一些嵌入式面试题目的集锦
    优先级反转
    struct和union的区别
    (转)typedef和#define的用法与区别
    const 和 #define区别
    白话经典算法系列之 快速排序 快速搞定
  • 原文地址:https://www.cnblogs.com/vs1435/p/12621256.html
Copyright © 2011-2022 走看看