怎样写出有逼格的水平居中

2017-09-04  本文已影响0人  早安马丁

水平居中在工作中运用非常频繁,往往标题、或者重要的内容都需要居中展示,美观且引人注目。那么你知道茴香豆的茴字,啊,呸。水平居中有几种写法吗?

1.外边距-margin:0 auto;

html:
<div class="box"></div>
css:
body{
    margin:0;
    font-size: 32px;
    line-height: 50px;
}
.box{
    margin:0 auto;
    width:300px;
    height:300px;
    background: #66ccff;
}
margin:auto水平居中.png

水平方向上margin的值为auto,浏览器自动计算横向外边距,使居中;
那么垂直方向上也赋予auto值,这样水平和垂直方向都居中了呢?哈哈哈,你很有想法,跟我学做.噢,不。你,你去试试呢。

Tip:
2.文本对齐方式-text-align:center;
html:
<div class="wrap">
    <a href="#">这是一个a标签</a><br>
    <span>这是一个内嵌标签</span><br>
    ![](https://img.haomeiwen.com/i7755028/fcbda6a06c684051.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</div>
css:
body{
    margin:0;
    font-size: 32px;
    line-height: 50px;
}
.wrap{
    width:100%;
    text-align: center;
    background-color: #66ccff;
}
text-align:center水平居中.png

 通过设定父级文本居中排列,行内元素以及行内块水平居中显示。

Tip:
3.相对定位-position:relative;
html:
<div class="box">
css:
body{
    margin:0;
}
.box{
    position: relative;
    left: 50%;
    top:0;
    margin-left: -200px;
    width:400px;
    height:300px;
    background-color: #66ccff;
}
position:relative水平居中.png

元素相对定位之后,根据自身的初始位置来计算坐标,左侧增加父级一般的宽度的距离,此时左边缘居中;使用margin的负值往左偏移自身一半的宽度,使其中心点居中。

Tip:
4.绝对定位-position:absolute;
html:
<div class="wrap">
    <span class="span">这是一个绝对定位的行内元素</span>
</div>
css:body{
    margin:0;
    font-size: 32px;
    line-height: 50px;
}
.wrap{
    position: relative;
    width:100%;
}
.span{
    position: absolute;
    left: 50%;
    top:0;
    margin-left: -200px;
    width:400px;
    height:300px;
    background-color: #66ccff;
}
position:absolute水平居中.png

 元素绝对定位之后,根据有定位的父级,来计算自己的坐标,左侧增加父级一般的宽度的距离,此时左边缘居中;使用margin的负值往左偏移自身一半的宽度,使其中心点居中。

Tip:
5.弹性盒模型的主轴对齐方式-justify-content:center;
html:
<div class="wrap">
    <div class="box">弹性盒模型子元素的水平居中</div>
</div>
css:
.wrap{
    display: -webkit-box; /*Safari 3.1-6 Android2.3 browser*/ 
    display: -moz-box; /*Firefox 19- */ 
    display: -ms-flexbox; /*IE 10 */ 
    display: -webkit-flex; /*Chrome 21+  */ 
    display: flex;/* 当前标准语法 */
        -moz-box-pack: center;
        -webkit-box-pack: center;
    justify-content: center;
    width:100%;
}
.box{
    width:500px;
    height:300px;
    background-color: #66ccff;
}
justify-content:center水平居中.png

元素在主轴的中心,多余空间在主轴的两侧;主轴默认水平方向,则子元素水平居中。

Tip:
上一篇 下一篇

猜你喜欢

热点阅读