a,----定位方式(父元素宽高固定,子元素宽高固定)
<div class="Father"> <div class="children"></div> </div> <style lang="scss" scoped> .Father{ position: relative; } .children{ 50px; height: 50px; position: absolute; top: 0px; bottom: 0px; left: 0px; right: 0px; margin: auto; } </style>
b, ----flex布局方式(父元素宽高不固定,子元素宽高不固定)
<div class="Father"> <div class="children"></div> </div> <style lang="scss" scoped> .Father { border: 1px solid red; height: 100px; display: flex; justify-content: center; align-items: center; } .children { 50px; height: 50px; border: 1px solid blue; } </style>
c, ----transform方式(父元素宽高不固定,子元素宽高不固定)
<div class="Father"> <div class="children"></div> </div> <style lang="scss" scoped> .Father { border: 1px solid red; height: 100px; position: relative; } .children { 50px; height: 50px; border: 1px solid blue; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* 使用css3的transform来实现 */ } </style>
.