CSS佈局 - 水平居中

1 text-align

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>水平居中-1</title>
    <style>
        .parent {
            text-align: center;
            background-color: green;
        }
        .child {
            display: inline-block;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">我是水平居中內容</div>
    </div>
</body>
</html>

在這裏插入圖片描述

2 margin

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>水平居中-2</title>
    <style>
        .parent {
            background-color: green;
        }
        .child {
            width: 200px;
            margin: 0 auto;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">我是水平居中內容</div>
    </div>
</body>
</html>

在這裏插入圖片描述

3 table

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>水平居中-3</title>
    <style>
        .parent {
            background-color: green;
        }
        .child {
            display: table;
            margin: 0 auto;
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">我是水平居中內容</div>
    </div>
</body>
</html>

在這裏插入圖片描述

4 absolut

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>水平居中-4</title>
    <style>
        .parent {
            position: relative;
            background-color: green;
        }
        .child {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">我是水平居中內容</div>
    </div>
</body>
</html>

在這裏插入圖片描述

5 flex

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>水平居中-5</title>
    <style>
        .parent {
            display: flex;
            justify-content: center; 
            background-color: green;
        }
        .child {
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="parent">
        <div class="child">我是水平居中內容</div>
    </div>
</body>
</html>

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章