置中篇 - 範例
這篇主要簡單帶過幾種置中的方式:
範例1、Display - Flex
<div class="main">
<div class="box"></div>
</div>
*,*::after,*::before
{
box-sizing: border-box;
}
body{
margin: 0;
padding: 0;
}
.main{
position: relative;
height: 100vh;
background-color: #555;
display: flex;
justify-content: center;
align-items: center;
}
.box{
position: relative;
height: 200px;
width: 200px;
background-color: plum;
}
範例2、Display - Grid
<div class="main">
<div class="box"></div>
</div>
*,*::after,*::before
{
box-sizing: border-box;
}
body{
margin: 0;
padding: 0;
}
.main{
position: relative;
height: 100vh;
background-color: #555;
display: grid;
}
.box{
position: relative;
height: 200px;
width: 200px;
justify-self: center;
align-self: center;
background-color: plum;
}
範例2-1
<div class="main">
<div class="box"></div>
</div>
*,*::after,*::before
{
box-sizing: border-box;
}
body{
margin: 0;
padding: 0;
}
.main{
position: relative;
height: 100vh;
background-color: #555;
display: grid;
}
.box{
position: relative;
height: 200px;
width: 200px;
margin: auto;
background-color: plum;
}
範例2-2
<div class="main">
<div class="box"></div>
</div>
*,*::after,*::before
{
box-sizing: border-box;
}
body{
margin: 0;
padding: 0;
}
.main{
position: relative;
height: 100vh;
background-color: #555;
display: grid;
}
.box{
position: relative;
height: 200px;
width: 200px;
margin: auto;
background-color: plum;
}
範例3position -relative
<div class="wrap">
<div class="box"></div>
</div>
body {
margin: 0;
padding: 0;
background-color: #555;
}
.wrap {
position: relative;
width: 1200px;
height: 100vh;
margin-left: auto;
margin-right: auto;
background-color: #aaa;
}
.box {
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
position: fixed;
width: 200px;
height: 200px;
background-color: #fff;
}
範例3-1
<div class="wrap">
<div class="box"></div>
</div>
body {
margin: 0;
padding: 0;
background-color: #555;
}
.wrap {
position: relative;
width: 1200px;
height: 100vh;
margin-left: auto;
margin-right: auto;
background-color: #aaa;
}
.box {
position: fixed;
left: 50%;
top: 50%;
transform:translate(-50%,-50%);
width: 200px;
height: 200px;
background-color: #fff;
}
範例3-2
<div class="main">
<div class="box"></div>
</div>
*,*::after,*::before
{
box-sizing: border-box;
}
body{
margin: 0;
padding: 0;
}
.main{
position: relative;
height: 100vh;
background-color: #555;
}
.box{
position: relative;
height: 200px;
width: 200px;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: plum;
}
Last updated