zoukankan      html  css  js  c++  java
  • 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规则,就能完美居中
    //此效果还可以用它来居中图片。

    效果图:

  • 相关阅读:
    【转】PHP使用共享内存进程间通信
    【转】php进程间通信--有名管道
    【转】代理模式-php白话示例
    [转]设计的核心任务之三:确保正交性
    pc主板支持独显和集显视频输出
    OpenGL核心技术之抗锯齿
    读书:有钱人想的和你不一样
    js 文本相似度
    js实现获得QQ截图或者微信截图后剪切板的内容clipboardData
    【转】chrome浏览器F12 Network中Timing参数含义
  • 原文地址:https://www.cnblogs.com/rain-null/p/6930844.html
Copyright © 2011-2022 走看看