• css 元素居中各种办法


    一:通过弹性布局
    <
    style> #container .box{ width: 80px; height: 80px; position: absolute; background:red; } #container{ background:green;width: 250px;height: 250px;border: 1px solid khaki;

    //下面三行是核心代码 display: flex; justify-content: center; align-items: center; } </style> </head> <body> <div id="container"> <div class="box"> </div></div> 效果如下:

      
    二、通过绝对定位来水平居中一个块级元素,(知道元素宽度,高度)。

    <style> #container .box{ width: 80px; height: 120px;
             background:red; position: absolute; top: 50%; left: 50%; background:red; margin-top: -60px; // 这二行可以用 transform: translate(-50%,-50%);代替分别对应x,y即宽高的一半 margin-left: -40px; } #container{ position:relative;background:green;width: 250px;height: 250px;border: 1px solid khaki; </style> </head> <body> <div id="container"> <div class="box"> </div></div>
    效果图如下:

    垂直居中单行文字

    <div>
    <span>这是居中的单行文字<span>
    </div>
    
    <style>
    div{width:300px;height:200px;background:#66f;color:white;}
    span {line-height:200px}
    </style>
    //这里通过父元素高度(height)与文字行高(line-height)相等做到的

    效果图:

    多行文字的居中

    <div>
    <p>这是居中的多行文字
    这是居中的多行文字
    这是居中的多行文字
    这是居中的多行文字<p>
    
    </div>
    <style>
    div{width:300px;height:200px;background:#66f;color:white;
    display:table
    }
    p{vertical-align:middle;display:table-cell} </style>
    //这里通过为父元素设置display:table,把多行文字用p元素包裹然后运用只对表格单元格有效的
    vertical-align:middle的css规则,就能完美居中
    //此效果还可以用它来居中图片。

    效果图:

  • 相关阅读:
    搜索引擎
    Mybatis springmvc面试题
    spring框架面试题
    数据库
    javaWEB面试题
    JavaWeb
    SpringCloud2
    网络
    比特币网络架构及节点发现分析
    Github推荐一个国内牛人开发的超轻量级通用人脸检测模型
  • 原文地址:https://www.cnblogs.com/rain-null/p/6930844.html
Copyright © 2020-2023  润新知