先给出HTML结构布局
<div class="par"> <div class="child">我是子元素</div> </div>
.par{ text-align: center; } .child{ background-color: tomato; display:inline-block; }
将子元素设置为inline-block
这样既能够像块元素同样设置盒模型,又能够像行内元素同样试用text-align:center
进行居中flex
将子元素设置为inline-block
后,子元素为块级元素,宽度为内容宽度code
.par{ } .child{ background-color: tomato; display:table; margin:0 auto; }
table
元素是块级元素,宽度自适应为内容宽度,因此经过display:table
对子元素进行转换并设置块元素居中标配margin:0 auto
orm
.par{ position: relative; } .child{ background-color: tomato; width:300px; position: absolute; left:50%; transform: translateX(-50%); }
因为子元素是个块级元素(div),默认占满父元素宽度,因此咱们将子元素宽度设为300pxit
原理很简单,先用绝对定位将子元素置于距父元素左边界一半的位置,而后再将子元素向左移动自身的一半,达到居中效果io
注意,position:relative
将父元素设为子元素绝对定位的参照物table
.par{ display:flex; justify-content: center; } .child{ background-color: tomato; }
因为flex-grow
属性默认值为0,flex-basis
属性默认值为auto,因此宽度为内容宽度(在没有设置指定值时,不然为指定值)form
顺便说一句,flex很强大class
高度为元素高度,就不指定具体值了原理
.par{ height:500px; display:table-cell; vertical-align:middle; } .child{ background-color: tomato; }
子元素宽度为内容宽度,父元素宽度为子元素宽度
.par{ height:500px; position: absolute; } .child{ background-color: tomato; width:300px; position: absolute; top:50%; transform: translateY(-50%); }
不指定子元素宽度的话,子元素的内容将纵向展现
.par{ height:500px; display:flex; align-items:center; } .child{ background-color: tomato; width:300px; }
上述两种居中布局的结合
.par{ width:500px; height:500px; border:1px solid #ccc; text-align: center; display: table-cell; vertical-align: middle; } .child{ background-color: tomato; width:300px; display:inline-block; }
.par{ width:500px; height:500px; border:1px solid #ccc; position: relative; } .child{ background-color: tomato; width:300px; position: absolute; left:50%; top:50%; transform: translate(-50%,-50%); }
.par{ width:500px; height:500px; border:1px solid #ccc; display:flex; justify-content: center; align-items: center; } .child{ background-color: tomato; width:300px; }
有问题欢迎提问,实践出真知