垂直居中的几种实现方式

栏目: Html · 发布时间: 6年前

内容简介:相比较水平居中,垂直居中比较复杂点。尤其是在实际页面中,有很多特殊的场景,导致水平居中实现起来比较麻烦。这篇文章旨在纪录一些我知道的居中方式。以一道经典面试题为例:一个200*200的div在一个div水平垂直居中,用css实现。缺点:必须知道居中元素的实际大小。根据实际大小用margin进行调整,因为top,left是以元素的上边框进行计算的。优点:利用transform改良上面那种必须知道元素大小的限制。

相比较水平居中,垂直居中比较复杂点。尤其是在实际页面中,有很多特殊的场景,导致水平居中实现起来比较麻烦。这篇文章旨在纪录一些我知道的居中方式。以一道经典面试题为例:一个200*200的div在一个div水平垂直居中,用css实现。

首先定义元素

<!--dom层:和垂直居中无关的样式直接定义在style里。-->
<body>
    <div class="margin" style="width: 500px;height: 500px;background-color: aqua">
        <div class="center" style="width: 200px;height: 200px;background-color: antiquewhite"></div>
    </div>
</body>

1.百分比的方式

缺点:必须知道居中元素的实际大小。根据实际大小用margin进行调整,因为top,left是以元素的上边框进行计算的。

<style>
    .center {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-left: -100px;
    }
    
    .margin{
      position: relative;    //外层元素必须定义为relative,否则是相对整个屏幕水平垂直居中
    }
</style>

2.百分比结合transform

优点:利用transform改良上面那种必须知道元素大小的限制。

<style>
    .center{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    .margin{
      position: relative;
    }
</style>

3.flex布局

Flex布局(弹性布局),作为css3新增的布局方式,能很好的支持不同的屏幕大小,绝对是现在的前端工程师必备技能。

<style>
    .margin {
            display: flex;
            justify-content: center;
            align-items: Center;
        }
  </style>

4.flex布局结合margin

.margin{
            display: flex;
        }
        
    .center{
            margin: auto;
        }

5.绝对定位和0

.margin{
            position: relative;
        }

    .center{
            overflow: auto;
            margin: auto;
            position: absolute;
            top: 0; left: 0; bottom: 0; right: 0;
       }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Domain-Driven Design

Domain-Driven Design

Eric Evans / Addison-Wesley Professional / 2003-8-30 / USD 74.99

"Eric Evans has written a fantastic book on how you can make the design of your software match your mental model of the problem domain you are addressing. "His book is very compatible with XP. It is n......一起来看看 《Domain-Driven Design》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具