上下左右居中对齐

display:  inline/inline-block

将父元素(容器)设定 text-align: center; 即可左右置中。

display: block

将元素本身的 margin-left 和 margin-right 设定为auto; 即可左右置中。


方法一:Position: Absolute 对齐元素本身

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>上下左右居中对齐</title>
        <style type="text/css">
            #box {
                width: 100px;
                height: 100px;
                border: 2px solid #0000FF;
            }
            
            #box {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translateX(-50%) translateY(-50%);
               
             /* 或者这样写 */
                right: 50%;
                bottom: 50%;
                transform: translateX(50%) translateY(50%);
            }
           
        </style>
    </head>
    <body>
            <div id="box"></div>    
    </body>
</html>

方法二:Flexbox 对齐元素内容

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>上下左右居中对齐</title>
        <style type="text/css">
            #box {
                width: 100px;
                height: 100px;
                border: 2px solid #0000FF;
            }
            body {
                min-height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
            }
        </style>
    </head>
    <body>
            <div id="box"></div>    
    </body>
</html>

方法三:Display : Table 对齐元素内容

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>上下左右居中对齐</title>
        <style type="text/css">
            #box {
                width: 100px;
                height: 100px;
                border: 2px solid #0000FF;
                display: inline-block;
            }
            body {
                display: table;
                width: 100%;
                min-height: 100vh;
                margin: 0;
            }
            
            .cell {
                display: table-cell;
                vertical-align: middle;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div class="cell">
            <div id="box"></div>
        </div>    
    </body>
</html>
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇