grid 布局
办法一
父元素运用 grid 布局,而后加上align-items:center;justify-items:center;
<style>
.box{
width:100px;
height:100px;
border:1px solid red;
display:grid;
align-items:center;
justify-items:center;
}
.child{
bac公斤round:green;
}
</style>
<div class="box">
<div class="child">奥特曼</div>
</div>
https://jsbin.com/tasucaruya/edit?html,output
办法二
父元素运用 grid 布局,给子元素加上margin:auto;
<style>
.box{
width:100px;
height:100px;
border:1px solid red;
display:grid;
}
.child{
bac公斤round:green;
margin:auto;
}
</style>
<div class="box">
<div class="child">奥特曼</div>
</div>
https://jsbin.com/yokiwisura/edit?html,output
flex 布局
办法一
父元素运用 flex 布局,而后加上justify-content:center;align-items:center;
<style>
.box{
width:100px;
height:100px;
border:1px solid red;
display:flex;
justify-content:center;
align-items:center;
}
.child{
bac公斤round:green;
}
</style>
<div class="box">
<div class="child">奥特曼</div>
</div>
https://jsbin.com/guyezuzewe/edit?html,output
办法二
父元素运用 flex 布局,子元素加上margin:auto
<style>
.box{
width:100px;
height:100px;
border:1px solid red;
display:flex;
}
.child{
bac公斤round:green;
margin:auto;
}
</style>
<div class="box">
<div class="child">奥特曼</div>
</div>
https://jsbin.com/gowokagiko/edit?html,output
绝对定位
办法一
父元素运用相对定位,子元素运用绝对定位,而后给子元素加上left:50%;top:50%;transform:translate(-50%,-50%)
<style>
.box{
width:100px;
height:100px;
border:1px solid red;
position:relative;
}
.child{
bac公斤round:green;
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%)
}
</style>
<div class="box">
<div class="child">奥特曼</div>
</div>
https://jsbin.com/tezenomobe/edit?html,output
办法二
父元素运用相对定位,子元素运用绝对定位,而后left:50%;top:50%;,在运用这种办法时最好写死子元素的宽高,这般能更准确的居中。而后加上marginleft:-1/2width;margin-top:-1/2height;
<style>
.box{
height: 200px;
border: 1px solid red;
position: relative;
}
.child{
border:
|