zoukankan      html  css  js  c++  java
  • html,将元素水平,垂直居中的四种方式

      将元素垂直,水平居中分两种情况:一个是元素尺寸固定,二是元素尺寸不固定

    一.尺寸固定

    方法1:定位 ,50%,margin负距

    .box{
    400px;
    height: 300px;
    border: 2px solid black;
    /* 把元素变成定位元素 */
    position: absolute;
    /* 元素距离上,左都为50% */
    left: 50%;
    top: 50%;
    /* 让元素的左外边距,上外边距为元素宽高的1/2 注意margin是负距*/
    margin-top: -150px;
    margin-left: -200px;
    }

    图解:

     方法2:四方为都为0 ,margin:auto

    .box{
    400px;
    height: 300px;
    border: 2px solid black;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    }

    图解:

    3 方法三,元素尺寸不固定

    .box2 {
    position: absolute;
    left: 50%;
    top: 50%;
    /* 设置元素的相对于自身的偏移度为负50%(也就是元素自身尺寸的一半)*/
    transform: translate(-50%, -50%);
    }

    4.方法四:使用伪元素 利用inline-block与vertical-align配合伪元素达到垂直居中

    /* 背景左右居中 */
    .dialog_container {
    text-align: center;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
    100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.35);
    }
    /* 伪元素上下居中 */
    .dialog_container:after {
    display: inline-block;
    0;
    height: 100%;
    content: "";
    vertical-align: middle;
    }

    /* 真正居中的元素 */
    .dialog_box {
    display: inline-block;
    vertical-align: middle;
    text-align: left;
    border: 1px solid black;
    }

    补充:将元素水平居中比较简单

    1.块级元素居中 margin 和width配合

     2.内联元素居中 给其父级元素加text-align:center

  • 相关阅读:
    2017-3-7 leetcode 66 119 121
    2017-3-6 leetcode 118 169 189
    2017-3-5 leetcode 442 531 533
    c++ std
    2017-3-4 leetcode 414 485 495
    2017-3-3 leetcod 1 35 448
    想做手游
    编程规范
    1165: 零起点学算法72——首字母变大写
    1164: 零起点学算法71——C语言合法标识符(存在问题)
  • 原文地址:https://www.cnblogs.com/SallyShan/p/11480685.html
Copyright © 2011-2022 走看看