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规则,就能完美居中
//此效果还可以用它来居中图片。

效果图:

原文地址:https://www.cnblogs.com/rain-null/p/6930844.html