• css实现div水平垂直居中


      中秋快到了,祝大家中秋快乐。

      平时大家写bug过程中肯定会遇到让div框水平或者垂直居中,然而有时候能居中,有时候不能居中。我把平时遇到的一些方法写出来,如果对你有用,那便是晴天。

      1、text-align: center;

    text-align: center;

      这个是最简单的了,实现文本水平居中。

      2、margin: 0 auto;

      0为上下边距为0,auto为左右边距自适应,于是变实现了水平居中。高度固定时,加上line-height就能实现垂直居中。代码如下:

    1 margin: 0 auto;
    2 height: 100px;
    3 line-height: 100px;<!-- 高度固定时使用 -->

      3、子元素基于父元素实现居中

      采用绝对定位,使子div框定位跟着父div框,再让子div框左右边距自适应,于是边形成了水平垂直居中。

      效果如图1所示。

    图1

      代码如下:

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4   <meta charset="UTF-8">
     5   <meta name="viewport" content="width=device-width, initial-scale=1.0">
     6   <meta http-equiv="X-UA-Compatible" content="ie=edge">
     7   <title>Document</title>
     8   <style>
     9     .parent {
    10        200px;
    11       height: 200px;
    12       border: 1px red solid;
    13       margin:0 auto;
    14       position: relative
    15     }
    16     .child {
    17        100px;
    18       height: 100px;
    19       border: 1px red solid;
    20       position:absolute;
    21       left: 0;
    22       right: 0;
    23       top:0;
    24       bottom:0;
    25       margin-left: auto;
    26       margin-right: auto;
    27       margin-top:auto;
    28       margin-bottom:auto;
    29     }
    30   </style>
    31 </head>
    32 <body>
    33   <div class="parent">
    34     <div class="child">
    35     </div>
    36   </div>
    37 </body>
    38 </html>

      4、弹性盒子实现居中

    1 display: flex;
    2 align-items: center; /*定义父元素的元素垂直居中*/
    3 justify-content: center; /*定义子元素的里的元素水平居中*/

      还有使用absolute与transform配合实现居中的,看小伙伴自己选择了。

      本文到这里就结束了,中秋快乐,有缘再会。

  • 相关阅读:
    Python全栈开发之---mysql数据库
    python爬虫项目(scrapy-redis分布式爬取房天下租房信息)
    python多线程爬虫+批量下载斗图啦图片项目(关注、持续更新)
    python爬虫+数据可视化项目(关注、持续更新)
    超融合基本架构简单定义
    开启新生之路,,,学习网络
    Redhat7.2 ----team网卡绑定
    设计原则
    java应用程序的运行机制
    java三大版本和核心优势
  • 原文地址:https://www.cnblogs.com/yyzhiqiu/p/11497511.html
Copyright © 2020-2023  润新知