CSS 元素置中

更新於 發佈於 閱讀時間約 3 分鐘

以下展示三種置中方法 :

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%;
}
留言
avatar-img
留言分享你的想法!
avatar-img
郭欣玫的沙龍
3會員
17內容數
郭欣玫的沙龍的其他內容
2024/07/24
主要來講宣告函式跟箭頭函式 : 宣告函式(Function Declaration) 語法: function functionName(parameters) { return result; } 特點: 使用 function 關鍵字 函式名稱是必需的 存在函式
2024/07/24
主要來講宣告函式跟箭頭函式 : 宣告函式(Function Declaration) 語法: function functionName(parameters) { return result; } 特點: 使用 function 關鍵字 函式名稱是必需的 存在函式
2024/07/14
就是指變數可以被訪問和使用的範圍,來說一下var、let和const的作用域差異。 var :function example() { console.log(x); // 輸出: undefined 因為變量提升造成的 var x = 5; } 函數作用域或全域作用域 可以重複宣告
2024/07/14
就是指變數可以被訪問和使用的範圍,來說一下var、let和const的作用域差異。 var :function example() { console.log(x); // 輸出: undefined 因為變量提升造成的 var x = 5; } 函數作用域或全域作用域 可以重複宣告
2024/07/04
一開始你先把你的專案push上去後,修改vite.config.ts ,要在裡面新增  base: "/Cart/" (/放自己的專案名稱/) build: {outDir: "docs"}, 接下來你要去你的github setting 裡面 -> Page ->選Deploy fro
Thumbnail
2024/07/04
一開始你先把你的專案push上去後,修改vite.config.ts ,要在裡面新增  base: "/Cart/" (/放自己的專案名稱/) build: {outDir: "docs"}, 接下來你要去你的github setting 裡面 -> Page ->選Deploy fro
Thumbnail
看更多