方法一:
关键词:display: grid; justify-items:center
范例:
<div class="box">
<p>hello</p>
</div>
.box {
width: 300px;
height: 300px;
border: 1px solid;
display: grid;
align-items: center;
justify-items: center;
}
p {
background: pink;
border: 2px blue solid;
}
方法二:
关键词:display: grid; justify-content:center
要明白方法一和方法二之间的区别 虽然效果是完全一样的 但是逻辑是不一样的
<div class="box">
<p>hello</p>
</div>
.box {
width: 300px;
height: 300px;
border: 1px solid;
display: grid;
align-items: center;
justify-content: center;
}
p {
background: pink;
border: 2px blue solid;
}
方法三:关键词:display: grid;只设置grid布局,外加`margin: auto;
<div class="box">
<p>hello</p>
</div>
.box {
width: 300px;
height: 300px;
border: 1px solid;
display: grid;
}
p {
background: pink;
margin: auto;
}
方法四:关键词:display: flex; justify-content:center
<div class="box">
<p>hello</p>
</div>
.box {
width: 300px;
height: 300px;
border: 1px solid;
display: flex;
align-items: center;
justify-content: center;
}
p {
background: pink;
border: 2px blue solid;
}
方法五:关键词:display: flex;只设置grid布局,外加`margin: auto;
<div class="box">
<p>hello</p>
</div>
.box {
width: 300px;
height: 300px;
border: 1px solid;
display: flex;
}
p {
background: pink;
margin: auto;
}
方法六:关键词:position: relative;