四種在 <div> 容器中控制內部元素排列的 CSS 技巧
✅ 使用方式、🎯 使用時機、🧾 常見指令集
項目 說明
💡 原理 利用 text-align 對 內聯元素(inline、inline-block) 進行對齊控制
🎯 使用時機 元素為 文字、按鈕、圖片(inline 或 inline-block) 並需置中時
🧾 常用指令
.container {
text-align: center;
padding: 20px; /* 增加上下間距 */
}
項目 說明
💡 原理 元素脫離標準流動,浮到左或右,其他內容會環繞在旁邊
🎯 使用時機 元素要排列在 左邊/右邊,但不太考慮垂直對齊(如圖片+文字混排)
🧾 常用指令
.left {
float: left;
}
.right {
float: right;
}
/* 避免父元素高度塌陷 */
.container::after {
content: "";
display: block;
clear: both;
}
項目 說明
💡 原理 使用 position 精準地控制元素位置,脫離標準排版方式
🎯 使用時機 元素需要絕對位置(corner 或浮在畫面某處),如圖示、提示框、貼標
🧾 常用指令
.container {
position: relative;
/* 母盒將由向外擴張的子盒,限制在盒內*/
}
.box {
position: absolute;
top: 10px;
left: 20px;
}
.box1 {
position: absolute;
top: 10px;
right: 20px;
}
項目 說明
💡 原理 將容器設定為 display: flex,元素會在主軸方向排列
🎯 使用時機 要控制「左右排列、等距、置中、對齊」時,是現代網頁最常用方式
🧾 常用指令
.container {
display: flex;
justify-content: space-between; /* 主軸對齊方式 */
align-items: center; /* 垂直對齊方式 */
/* 在母盒下指令,控制子盒*/
}
box{}
box2{}
justify-content 可選值:
flex-start:左對齊
center:置中
space-between:首尾對齊,中間平均
align-items 可選值:
center:垂直置中
flex-start / flex-end:上對齊 / 下對齊
/* 第一種方式 text-align: padding */
/* 第二種方式 float*/
/* 第三種方式 position */
/* 第四種方式 flex*/
以為例
html
<div class="footer">
<h2>企鵝樹家族餐飲集團</h2>
<h3>版權所有‧請勿任意轉載</h3>
</div>
<h3>http://www.penguintree.com.tw/</h3>
css
.footer {}
.footer h2 {}
.footer h3 {}
要求請用以上四種方式,要求
.footer的高度為80px
.footer h2,左邊距20px
.footer h3靠右,右邊距20px
<h3>網址不能進入DIV