zoukankan      html  css  js  c++  java
  • position:absolute和margin:auto 连用实现元素水平垂直居中

    有时候,要实现一些元素水平垂直都居中,这部分元素呢 可能大小未知,例如一些图片或者是一些未知大小的块元素。

    利用绝对定位可以将要居中的元素脱离文档流.

     position: absolute;
     left:0px;
     right: 0px;
     top:0px;
     bottom: 0px;

    但他的父元素要设成相对定位

    position: relative;

    这样设置完成后 会发现子元素并没有居中。这是因为虽然脱离了文档流但是top的bottom的值是相等的。根据优先级会自动向上对齐。同理左右也是如此。

    这时在要居中的元素中加上

    margin:auto;

    margin:auto会自动去计算子元素和父元素之间的边距,并设为居中。所以就会实现上下左右都居中。

    那么还有一个问题,既然居中是有margin:auto来计算实现。为什么还需要将元素设为绝对定位呢?

    这是因为margin:auto 默认只会计算左右边距。而上下如果设置为auto时默认是取0.也就是说,margin:auto和margin:0 auto 在一般情况下没有区别,不能实现垂直居中。

    但是有了绝对定位后,margin-top和margin-bottom 的值就不是0了,也是通过计算所得。所以能实现垂直居中。

    最后,发出完整的css类

    .center{
                   position: absolute;
                   left:0px;
                   right: 0px;
                   top:0px;
                   bottom: 0px;
                   margin:auto;
                   background: pink;
                   text-align: center;
                   vertical-align:middle;
        }

    晚安,世界

  • 相关阅读:
    浅谈CSS3 Filter的10种特效
    简评Photoshop CC新增的复制CSS功能
    首页背景图自适应
    CSS常用浮出层的写法
    隐藏"站长统计"图标
    响应式网站代码收集整理
    【leetcode❤python】 58. Length of Last Word
    【leetcode❤python】 88. Merge Sorted Array
    【leetcode❤python】 234. Palindrome Linked List
    【leetcode❤python】 20. Valid Parentheses
  • 原文地址:https://www.cnblogs.com/ada-blog/p/7242664.html
Copyright © 2011-2022 走看看