Home > Web Front-end > HTML Tutorial > 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?

一个新手
Release: 2017-10-20 09:14:17
Original
1249 people have browsed it

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>
Copy after login

 

Use translate


<style>
    .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%);
    }
</style>
<p class="transform-box"></p>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template