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

How to center horizontally and vertically absolutely positioned elements

高洛峰
高洛峰Original
2017-02-24 13:35:071303browse

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>

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>

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>

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