继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

CSS居中的方法总结

UYOU
关注TA
已关注
手记 295
粉丝 86
获赞 458

CSS水平和垂直居中在开发中经常用到,在此加以总结。

水平居中方法

1.行内元素水平居中,设置父元素的text-align: center

<div id="box" >
  <span id="content" >center</span></div>
#box {  text-align: center;
}

常用的行内元素有aabbrbbreminputlabelselectspanstrongsubsuptextarea等。

2.宽度固定的块级元素水平居中,设置该元素的margin: 0 auto

<div id="box" >
  <div id="content" >center</div></div>
#box {  width: 64%;  margin: 0 auto;
}

常用的块级元素有addressarticleaudioblockquotecanvasdivfooterformh1headerhroloutputppresectiontableulvideo等。

3.绝对定位元素水平居中,设置父元素position: relative,设置该元素left: 0; right: 0; margin: 0 auto;

<div id="box" >
  <div id="content" >center</div></div>
#box {  position: relative;
 }#content {  position: absolute;  left: 0;  right: 0;  margin: 0 auto;
}

4.flex布局水平居中,设置父元素display: flex; justify-content: center

<div id="box" >
  <div id="content" >center</div></div>
#box {  display: flex;  justify-content: center;
}

垂直居中方法

1.单行文本垂直居中,设置该元素line-height为父元素height高度。

<div id="box" >
  <div id="content" >center</div></div>
#content {  height: 2em;  line-height: 2em;
}

2.将父元素显示为表格display: table-cell,利用vertical-align: middle设置垂直居中。

<div id="box" >
  <div id="content" >center</div></div>
#box {  display: table-cell;  vertical-align: middle;
 }

3.绝对定位该元素并设置父元素positoin: relative,设置该元素top:0; bottom: 0; margin: auto;

<div id="box" >
  <div id="content" >center</div></div>
#box {  position: relative;
 }#content {  position: absolute;  top: 0;  bottom: 0;  marigin: auto;
}

4.绝对定位固定高度是,设置top: 50%margin-top值为高度值的一半。

<div id="box" >
  <div id="content" >center</div></div>
#box {  position: relative;
 }#content {  position: absolute;  height: 12em;  top: 50%;  margin-top: 6em;
}

5.flex布局,设置父元素display: flex; align-items: center

<div id="box" >
  <div id="content" >center</div></div>
#box {  display: flex; 
  align-items: center;
 }



作者:Adambee08
链接:https://www.jianshu.com/p/c38dcdd3d89b


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP