CSS实现居中样式

2019-03-19  本文已影响0人  小q

html代码部分

<div class="box1">
    行内元素水平居中
</div>

css代码部分

.box1{
    width: 200px;
    height: 200px;
    background: tomato;
    text-align: center;
}   
<div class="box2">
    <div class="boy2">块元素水平居中</div>
</div>

css代码部分

.box2{
    width: 200px;
    height: 200px;
    background: tomato;
}
.boy2{
    width: 100px;
    height: 100px;
    background: skyblue;
    margin: 0 auto;
}

html代码部分

<div class="box2">
    <div class="boy2">块元素水平居中</div>
</div>

css代码部分

.box3{
    width: 200px;
    height: 200px;
    background: tomato;
    
}
.boy3{
    width: 100px;
    height: 100px;
    background: skyblue;
    display: table;
    margin: 0 auto;
}

方法三:将子元素设置成inline-block,父元素设置为text-align: center
html代码部分

<div class="box4">
    <div class="boy4">块元素水平居中</div>
</div>

css代码部分

.box4{
    width: 200px;
    height: 200px;
    background: tomato;
    text-align: center;
}
.boy4{
    width: 100px;
    height: 100px;
    background: skyblue;
    display: inline-block;
}

方法四:利用弹性盒实现水平居中
html代码部分

<div class="box8">
    <div class="boy8">弹性盒水平居中</div>
</div>

css代码部分

.box8{
    width: 200px;
    height: 200px;
    background: tomato;
    display: flex;
    justify-content:center;
}
.boy8{
    width: 100px;
    height: 100px;
    background: skyblue;
}

方法:设置与高度相同的行高
html代码部分

<div class="box5">
     行内垂直居中
</div>

css代码部分

.box5{
    width: 200px;
    height: 200px;
    background: tomato;
    line-height: 200px;
}

方法一:父元素设置成table-cell,再用vertical-align:middle
html代码部分

<div class="box6">
    <div class="boy6">块元素垂直居中</div>
</div>

css代码部分

.box6{
    width: 200px;
    height: 200px;
    background: tomato;
    display: table-cell;
    vertical-align: middle;
}
.boy6{
    width: 100px;
    height: 100px;
    background: skyblue;
}

方法二:弹性盒实现垂直居中
html代码部分

<div class="box7">
    <div class="boy7">弹性盒块元素垂直居中</div>
</div>

css代码部分

.box7{
    width: 200px;
    height: 200px;
    background: tomato;
    display: flex;
    align-items: center;
}
.boy7{
    width: 100px;
    height: 100px;
    background: skyblue;
}

水平居中记一下利用position的实现方法,剩余的有时间再补上吧,嘻嘻嘻。

方法:position设置0加margin的方法
html代码部分

 <div class="box9">
    <div class="boy9">margin,绝对定位和0实现居中</div>
 </div>

css代码部分

.box9{
    width: 200px;
    height: 200px;
    background: tomato;
    position: relative;
}
.boy9{
     width: 100px;
    height: 100px;
    background: skyblue;
    margin: auto; 
    position: absolute;
    left: 0; top: 0; right: 0; bottom: 0;   
}

后记

CSS居中的方法肯定不止这几种,只是把最常用的写了一下,后面学到其他的会继续补充。

上一篇 下一篇

猜你喜欢

热点阅读