这里行内元素是指文本text、图像img、按钮超连接等,只需给父元素设置text-align:center便可实现。布局
.center{ text-align:center; } <div class="center">水平居中</div>
定宽块级元素水平居中
只需给须要居中的块级元素加margin:0 auto便可,但这里须要注意的是,这里块状元素的宽度width值必定要有flex
.center{ width:200px; margin:0 auto; border:1px solid red; } <div class="center">水平居中</div>
不定宽块级元素水平居中
不定宽,即块级元素宽度不固定
方法1:设置tablespa
经过给要居中显示的元素,设置display:table,而后设置margin:0 auto来实现code
.center{ display:table; margin:0 auto; border:1px solid red; } <div class="center">水平居中</div>
方法2:设置inline-block(多个块状元素)
子元素设置inline-block,同时父元素设置text-align:centerorm
.center{ text-align:center; } .inlineblock-div{ display:inline-block; } <div class="center"> <div class="inlineblock-div">1</div> <div class="inlineblock-div">2</div> </div>
方法3:设置flex布局
只需把要处理的块状元素的父元素设置display:flex,justify-content:center;blog
.center{ display:flex; justify-content:center; } <div class="center"> <div class="flex-div">1</div> <div class="flex-div">2</div> </div>
方法4:position + 负margin;
方法5:position + margin:auto;
方法6:position + transform;图片
注:这里方法四、五、6同下面垂直居中同样的道理,只不过须要把top/bottom改成left/right,在垂直居中部分会详细讲述。it
经过设置父元素table,子元素table-cell和vertical-align
vertical-align:middle的意思是把元素放在父元素的中部io
方法1:flex布局
在须要垂直居中的父元素上,设置display:flex和align-items:center
要求:父元素必须显示设置height值table
显示效果:
方法2:利用position和top和负margin(需知宽高)
一、设置元素为absolute/relative/fixed
二、margin=负一半
效果以下:
方法3:利用position和top/bottom和margin:auto(注意不是margin:0 auto)
一、position:absolute/relative/fixed
二、top/bottom:0
三、margin:auto
效果以下:
方法4:利用position和top和transform
transform中translate偏移的百分比就是相对于元素自身的尺寸而言的。
效果以下:
方法1:绝对定位+margin:auto
div{ width: 200px; height: 200px; background: green; position:absolute; left:0; top: 0; bottom: 0; right: 0; margin: auto; }
方法2:绝对定位+负margin
div{ width:200px; height: 200px; background:green; position: absolute; left:50%; top:50%; margin-left:-100px; margin-top:-100px; }
方法3:绝对定位+transform
div{ width: 200px; height: 200px; background: green; position:absolute; left:50%; /* 定位父级的50% */ top:50%; transform: translate(-50%,-50%); /*本身的50% */ }
方法4:flex布局
.box{ height:600px; display:flex; justify-content:center; //子元素水平居中 align-items:center; //子元素垂直居中 /* aa只要三句话就能够实现不定宽高水平垂直居中。 */ } .box>div{ background: green; width: 200px; height: 200px; }
方法5:table-cell实现居中