web开发经常使用的几种居中形式

一 水平居中
二 水平垂直居中
三 针对文本内容的垂直居中html

一 水平居中

要居中的元素A有width属性

给元素A添加 margin:0,auto;(代码演示)浏览器

clipboard.png

ps: 此外,margin: auto;margin:0 auto;产生一样效果的缘由移步flex


要居中的元素B没有width属性

给B添加display:inline-block属性,并在B的外面包一层div且添加text-align:center;spa

clipboard.png

ps:text-align:center是让块状里面的元素(好比文字)居中。.net


要居中的元素C 是绝对定位的也就是其position为absolute

给C添加margin: auto; top:0; left:0; right:0; bottom:0;以及width和height属性 ,并确保C的外层父元素position: relative;code

clipboard.png

ps: htm

设置top,left,bottom,right 属性 把元素充满了容器,同时自身指定了宽度,总宽度(固定) = width(固定) + margin-left + margin-right;blog

当margin设置为auto的时候,左右边距会平分,元素天然就居中了(且是水平垂直居中)ip


二 水平垂直居中:

要居中的元素C没有width属性及height属性

给C的外层父元素添加display: flex; align-items: center; justify-content: center; 属性(注意浏览器的兼容性)get

clipboard.png

Or

给C添加margin: auto; 而且确保C的外层父元素 display: flex; (注意浏览器兼容性)

clipboard.png

ps: flexBox的知识请移步阮一峰大神的博客


针对文本内容的垂直居中:

父元素有width和height属性以及text-align: center; 同时给要居中的元素D添加line-height为父元素的height值

clipboard.png

ps: line-height 垂直居中原理 请移步


all.

by 潘小闲

相关文章
相关标签/搜索