zoukankan      html  css  js  c++  java
  • css 居中的汇总

    前言

    对css居中的几种方式汇总,并且分析适用情况。

    正文

    margin+position

    .CenterParent {
       position: relative;
       height: 200px;
        200px;
       background-color:yellow;
    }
    .CenterChild{
       position:absolute;
       height: 100px;
        100px;
       top:50%;
       left: 50%;
       margin-top:-50px;
       margin-left:-50px;
       background-color: red;
    }
    
    <div class="CenterParent">
    <div class="CenterChild">
    </div>
    </div>
    

    后续不展示效果。

    优点:兼容全部浏览器

    缺点:需要知道子元素的宽高。

    margin:aotu+postion

    .CenterParent {
       position: relative;
       height: 200px;
        200px;
       background-color:yellow;
    }
    .CenterChild{
       position:absolute;
       height: 100px;
        100px;
       top:0px;
       left: 0px;
       bottom: 0px;
       right: 0px;
       margin: auto;
       background-color: red;
    }
    

    中规中距:需要兼容的推荐。

    flex

    .CenterParent {
       display: flex;
       justify-content: center;
       align-items: center;
       height: 200px;
        200px;
       background-color:yellow;
    }
    .CenterChild{
       height: 100px;
        100px;
       background-color: red;
    }
    

    缺点:需要浏览器支持flex

    margin+transtion

    .CenterParent {
       position: relative;
       height: 200px;
        200px;
       background-color:yellow;
    }
    .CenterChild{
       position: absolute;
       top: 50%;
       left: 50%;
       transform:translate( -50%, -50%);
       height: 100px;
        100px;
       background-color: red;
    }
    

    缺点:需要支持transform

    table-cell

    .CenterParent {
       display: table-cell;
       text-align: center;
       vertical-align: middle;
       height: 200px;
        200px;
       background-color:yellow;
    }
    .CenterChild{
       100px;
      height: 100px;
      display: inline-block;
      background-color: red;
    }
    

    子元素必须是:inline-block或者inline.

  • 相关阅读:
    攻防世界web新手区前六关
    JS-数组基础知识3
    CSRF攻击的原理和spring security对CSRF攻击的解决方法
    Java开发微信公众号
    内部类
    Java Web整合开发(30) -- Spring的ORM模块
    win10安装mysql
    jquery 事件冒泡的介绍以及如何阻止事件冒泡
    jquery中attr和prop的区别介绍
    jQuery 层次选择器
  • 原文地址:https://www.cnblogs.com/aoximin/p/12447307.html
Copyright © 2011-2022 走看看