Home  >  Article  >  Web Front-end  >  What are the two ways to set the horizontal and vertical centering of an element?

What are the two ways to set the horizontal and vertical centering of an element?

一个新手
一个新手Original
2017-10-20 09:14:171181browse

The small requirement of making a horizontally and vertically centered modal pop-up box should be common for front-ends like us.

Before CSS3 came out, there was only one way (that I could think of) to center elements both horizontally and vertically, which was to use js calculations to position them in the middle of the screen. This method is clumsy and troublesome.

The following two methods can quickly position elements to the middle of the screen.

 flex layout


##

<style>
    .flex-mask {
        display: flex;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        align-items: center;  // 垂直居中
        justify-content: center;  // 水平居中
        background: rgba(0,0,0,.5);
    }
    .flex-box {
        width: 500px;
        height: 300px;
        background-color: #fff;
        border-radius: 10px;
    }
</style>

<!-- 元素 -->
<p class="flex-mask">
    <p class="flex-box"></p>
</p>

 

Use translate


c9ccee2e6ea535a969eb3f532ad9fe89
    .transform-box {
        position: fixed;
        z-index: 2;
        top: 50%;
        left: 50%;
        width: 300px;
        height: 150px;
        background-color: red;
        border-radius: 10px;
        transform: translate(-50%, -50%);
    }
531ac245ce3e4fe3d50054a55f265927
1496b9ead66877b9376ec97ce364601494b3e26ee717c64999d7867364b1b4a3

The above is the detailed content of What are the two ways to set the horizontal and vertical centering of an element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn