css垂直居中

2018-04-02  本文已影响7人  滚石_c2a6

一、Is it inline or inline-* elements (like text or links)? 是否行内元素
(1).Is it a single line? 单行文本垂直居中:
1.padding
.link {
padding-top: 30px;
padding-bottom: 30px;
}
2.line-height
.center-text-trick {
height: 100px;
line-height: 100px;
white-space: nowrap;
}
(2).Is it multiple lines? 多行垂直居中:

  1. display: table-cell;
    <div class="center-table">
    <p>I'm vertically centered multiple lines of text in a CSS-created table layout.</p>
    </div>
    <style>
    .center-table {
    display: table;
    height: 250px;
    background: white;
    width: 240px;
    margin: 20px;
    }
    .center-table p {
    display: table-cell;
    margin: 0;
    background: black;
    color: white;
    padding: 20px;
    border: 10px solid white;
    vertical-align: middle;
    }
    </style>
    代码:https://codepen.io/chriscoyier/pen/ekoFx
    2.flex
    不支持ie10以下,android 4.4以下,Safari Mobile 7.1以下
    .flex-center-vertically {
    display: flex;
    justify-content: center;
    flex-direction: column;
    height: 400px;
    }
    3.vertical-align: middle
    ::before support不支持ie9以下,注意 :before Safari Mobile不支持。
    .ghost-center {
    position: relative;
    }
    .ghost-center::before {
    content: " ";
    display: inline-block;
    height: 100%;
    width: 1%;
    vertical-align: middle;
    }
    .ghost-center p {
    display: inline-block;
    vertical-align: middle;
    }
    二、Is it a block-level element? 是否块元素
    (1).Do you know the height of the element?
    .parent {
    position: relative;
    }
    .child {
    position: absolute;
    top: 50%;
    height: 100px;
    margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
    }
    (2).Is the element of unknown height?
    .parent {
    position: relative;
    }
    .child {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    }
    (3).Can you use flexbox?
    .parent {
    display: flex;
    flex-direction: column;
    justify-content: center;
    }
    参考:https://css-tricks.com/centering-css-complete-guide/

附scss mixin:
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}

/* scss Mixin */
@mixin vertical-align($position: relative) {
position: $position;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}

.element p {
@include vertical-align();
}

from:http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

上一篇下一篇

猜你喜欢

热点阅读