Home > Web Front-end > CSS Tutorial > How to center horizontally and vertically absolutely positioned elements

How to center horizontally and vertically absolutely positioned elements

高洛峰
Release: 2017-02-24 13:35:07
Original
1327 people have browsed it

This article mainly introduces the method of horizontal and vertical centering of absolutely positioned elements. There are 3 methods for reference. Friends who need it can take a look.

1.css to achieve centering

Disadvantages: Need to know the width and height of the element in advance.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{
            width: 600px; 
            height: 400px;
            position: absolute; 
            left: 50%; top: 50%;
            border:1px solid #000;
            background:red;
            margin-top: -200px;    /* 高度的一半 */
            margin-left: -300px;    /* 宽度的一半 */
        }
    </style>
</head>
<body>
    <p class="box">
    </p>
</body>
</html>
Copy after login

2. CSS3 achieves horizontal and vertical centering

Note: Regardless of the size of the element Whatever it is, it can be centered. However, this writing method is only compatible with IE8 and above, and can be ignored on mobile terminals.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{
            width: 600px; 
            height: 400px;
            position: absolute; 
            left: 50%;
            top: 50%;
            border:1px solid #000;
            background:red;
            transform: translate(-50%, -50%);    /* 50%为自身尺寸的一半 */
        }
    </style>
</head>
<body>
    <p class="box">
    </p>
</body>
</html>
Copy after login

3. Margin: auto to achieve centering

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{
            width: 600px; 
            height: 400px;
            position: absolute; 
            left: 0;
            top: 0; 
            right: 0; 
            bottom: 0;
            border:1px solid #000;
            background:red;
            margin: auto;    /* 有了这个就自动居中了 */
        }
    </style>
</head>
<body>
    <p class="box">
    </p>
</body>
</html>
Copy after login

More For related articles on horizontal and vertical centering methods of absolutely positioned elements, please pay attention to 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