※ 各式置中方法與複習:
※ 建立center_practice專案:
1. margin: 0 auto:
index.html:
<body>
<!-- margin: 0 auto; 的置中方式 -->
<h2>1. margin: 0 auto; 的置中方式</h2>
<div class="outter">
<div class="box box1">讓我置中,拜託</div>
</div>
</body>
style.css:
.box1 {
display: block;
width: 200px;
margin: 0 auto;
}
成果顯示:
2. inline 系列:
index.html:
<body>
<!-- inline-block, inline 行内元素的置中方式 -->
<h2>2. inline-block, inline 行内元素的置中方式</h2>
<div class="outter outter2">
<div class="box box2">讓我置中,拜託</div>
</div>
</body>
style.css:
.outter2 {
text-align: center;
}
.box2 {
display: inline-block;
text-align: left;
}
成果顯示:
3. flex:
index.html:
<body>
<!-- flex 彈性排版的置中方式 -->
<h2>3. flex 彈性排版的置中方式</h2>
<div class="outter outter3">
<div class="box box3">讓我置中,拜託</div>
</div>
</body>
style.css:
.outter3 {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.box3 {
}
成果顯示:
4. position: absolute:
index.html:
<body>
<!-- position: absolute 絕對定位的置中方式 -->
<h2>4. position: absolute 絕對定位的置中方式</h2>
<div class="outter outter4">
<div class="box box4">讓我置中,拜託</div>
</div>
</body>
style.css:
.outter4 {
position: relative;
}
.box4 {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
成果顯示:
5. 文字的置中 :
index.html:
<body>
<!-- 文字的置中 -->
<h2>5. 文字的置中</h2>
<div class="outter">
<div class="box box5">讓我置中,拜託 </div>
</div>
</body>
style.css:
.box5 {
text-align: center;
line-height: 200px;
}
成果顯示: