水平垂直布局在前端开发中是经常使用到,在水平垂直布局中主要有两种情况,一种是知道元素的宽和高,一种是不知道宽高。
1. 已知宽高的元素进行水平垂直布局方案
方案一:
给父元素设置为相对定位,子元素设置绝对定位,且top,bottom,left和right为0,margin为auto
1 | <div id="fatherDom"> |
方案二:
设置父元素为相对定位,子元素设置为绝对定位,且left和top为50%,margin-left为元素宽度的一半(负值),margin-top为元素高度的一半(负值)。
1 | <div id="fatherDom"> |
方案三:
给父元素设置display为flex,justify-content为center,align-items 为center。
1 | <div id="fatherDom"> |
方案四:
使用calc计算属性, 父元素设置相对定位,子元素设置为绝对定位,left和top使用calc方法用50%减去宽高的一半。
1 | <div id="fatherDom"> |
2. 未知宽高的元素进行水平垂直布局方案
方案一:使用定位属性
给父元素设置为相对定位,子元素设置为绝对定位,且left和top为50%,transform设置为translateX和translateY为-50%;
1 | <div id="fatherDom"> |
方案二:
给父元素设置display为flex,justify-content为center,align-items 为center。
1 | <div id="fatherDom"> |
方案三:
给父元素设置display为table-cell, text-align为center,vertical-align为middle
1 | <div id="fatherDom"> |