CSS 代码如下:
.display-flex { /* OLD: Safari, iOS, Android browser, older WebKit browsers. */ display: -webkit-box; /* OLD: Firefox (buggy) */ display: -moz-box; /* MID: IE 10 */ display: -ms-flexbox; /* NEW, Chrome 21–28, Safari 6.1+ */ display: -webkit-flex; /* NEW: IE11, Chrome 29+, Opera 12.1+, Firefox 22+ */ display: flex; } /* 里面的直接子元素相对于外层容器 水平居中, 就可以不用table 让未知宽度的元素水平居中了 */ .display-flex.justify-content-center { -webkit-box-pack: center; -moz-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; } /* 里面的直接子元素相对于外层容器 垂直居中 */ .display-flex.align-items-center { -webkit-box-align: center; -moz-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; } /* 设置column 为竖向排列, 默认属性是row 横向排列 */ .display-flex.flex-direction-column { -webkit-box-orient: vertical; -webkit-box-direction: normal; -ms-flex-direction: column; -webkit-flex-direction: column; flex-direction: column; } /*让子元素都有相同的长度*/ .display-flex .flex1{ -webkit-box-flex: 1; -moz-box-flex: 1; -ms-box-flex: 1; -ms-neg-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; } .div-box{ height: 200px; border:1px solid red; } .div1{ height: 100px; background-color:red; }
HTML 的代码
例子1:
<!-- 什么都不加 --> <div class=‘div-box‘> <div class=‘div1‘>aaaa</div> <div class=‘div2‘>bbbb</div> </div>
例子2:
<!-- 只加 display-flex --> <div class=‘div-box display-flex‘> <div class=‘div1‘>aaaa</div> <div class=‘div2‘>bbbb</div> </div>
例子3:
<!-- 加 display-flex 和 flex1 --> <div class=‘div-box display-flex‘> <div class=‘div1 flex1‘>aaaa</div> <div class=‘div2 flex1‘>bbbb</div> </div>
例子4:
注意这个时候不要加 flex1, 否则居中看上去就不起作用了, 因为它们两个各占一半的宽度。
<!-- 加 display-flex 和 justify-content-center --> <div class=‘div-box display-flex justify-content-center‘> <div class=‘div1‘>aaaa</div> <div class=‘div2‘>bbbb</div> </div>
例子5:
<!-- 加 display-flex 和 align-items-center --> <div class=‘div-box display-flex align-items-center‘> <div class=‘div1‘>aaaa</div> <div class=‘div2‘>bbbb</div> </div>
例子6:
<!-- 加 display-flex 和 align-items-center 和 flex1 --> <div class=‘div-box display-flex align-items-center‘> <div class=‘div1 flex1‘>aaaa</div> <div class=‘div2 flex1‘>bbbb</div> </div>
例子7:
<!-- 加 display-flex 和 align-items-center 和 justify-content-center --> <div class=‘div-box display-flex align-items-center justify-content-center‘> <div class=‘div1‘>aaaa</div> <div class=‘div2‘>bbbb</div> </div>
例子8:
<!-- 加 display-flex 和 align-items-center 和 justify-content-center 和 flex-direction-column --> <div class=‘div-box display-flex align-items-center justify-content-center flex-direction-column‘> <div class=‘div1‘>aaaa</div> <div class=‘div2‘>bbbb</div> </div>
参考地址: https://www.smashingmagazine.com/2013/05/centering-elements-with-flexbox/
附几张兼容性属性的截图:
时间: 2024-10-13 00:31:27