2024-05-23|閱讀時間 ‧ 約 23 分鐘

CSS 元素置中

    以下展示三種置中方法 :

    raw-image


    <div class="method-container">
    <div class="method-title">Flexbox</div>
    <div class="box">
    <div class="dot"></div>
    </div>
    </div>

    <div class="method-container">
    <div class="method-title">Absolute </div>
    <div class="box box-absolute">
    <div class="dot"></div>
    </div>
    </div>

    <div class="method-container">
    <div class="method-title">Margin 0 Auto</div>
    <div class="box" style="position: relative; margin: 0 auto;">
    <div class="dot" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"></div>
    </div>
    </div>


    body {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 100vh;
    margin: 0;
    background-color: #f0f0f0;
    }

    .method-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    }

    .method-title {
    margin-bottom: 10px;
    font-weight: bold;
    }

    .box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 200px;
    height: 200px;
    border: 1px solid red;
    margin-bottom: 20px;
    }

    .box-absolute {
    position: relative;
    }

    .box-absolute div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    }

    .dot {
    width: 20px;
    height: 20px;
    background-color: red;
    border-radius: 50%;
    }
    分享至
    成為作者繼續創作的動力吧!
    © 2024 vocus All rights reserved.