css3上下垂直居中

CSS3中实现上下垂直居中已经很简单了,具体方法如下:

.container {
   position: relative;
   display: flex; /*使用flex布局*/
   justify-content: center;
   align-items: center; /*垂直居中*/
   height: 400px;
}

.item {
   width: 200px;
   height: 100px;
   background-color: #f2f2f2;
   text-align: center;
   font-size: 24px;
}

在上述代码中,我们先给容器(.container)设置了相对定位,并使用flex布局。其中,justify-content: center;让子元素水平居中,align-items: center;则是垂直居中的关键。

接下来,我们来看一下HTML代码:

<div class="container">
  <div class="item">居中内容</div>
</div>

在容器中放一个需要垂直居中的元素即可,这里我们假设这个元素的宽度为200px,高度为100px。

不过需要注意的是,这种垂直居中方式不兼容IE9以下浏览器,如果需要兼容,可以使用以下方式:

.container {
   position: relative;
   height: 400px;
}

.item {
   position: absolute; /*使用绝对定位*/
   top: 50%; /*上边距为50%*/
   transform: translateY(-50%); /*利用translate函数垂直居中*/
   width: 200px;
   height: 100px;
   background-color: #f2f2f2;
   text-align: center;
   font-size: 24px;
}

这种方式使用绝对定位和transform属性实现,相比于flex布局稍微繁琐一些,但也能实现垂直居中效果,并且兼容性比较好。

相关文章

Css常用的排序方式权重分配 排序方式: 1、按类型&#160;...
原文:https://www.cnblogs.com/wenruo/p/9732704.html 先上...
css属性:word-wrap:break-word; 与 word-break:break-all 的...
https://destiny001.gitee.io/color/
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML...
css之background的cover和contain的缩放背景图 对于这两个属...