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

  • 相关阅读:
    Internet Explorer 安全区域注册表项说明
    Android强制设置横屏或竖屏
    SQLite to Asp.net Entity Framework 部署问题
    获取地里位置信息
    通信API、使用Web Workers处理线程
    本地存储、离线应用程序
    多媒体播放
    绘制图形
    表单与文件
    HTML5的结构
  • 原文地址:https://www.cnblogs.com/SallyShan/p/11480685.html
Copyright © 2011-2022 走看看