盒模型居中方法总结
盒模型垂直水平居中的方法總結
- 1.使用margin指定具體值垂直水平居中
- 2.使用position + margin垂直水平居中
- 3.使用flex + margin垂直水平居中
- 4.使用flex+ justify-content或align-items垂直水平居中
- 5.使用position定位 + transform垂直水平居中
- 6.利用table-cell垂直水平居中
- 7.補充:使用行內塊 + text-align 水平居中
基本結構如下: <div class="father"><div class="son"></div> </div>
1.使用margin指定具體值垂直水平居中
注意:此處簡化說明,只給了父元素、子元素一個寬度,使用具體值時,應加上父元素、子元素的border的值。
需要指定margin-top、margin-left的值。把值寫死,維護性差。
樣式如下:
.father{background-color:lightblue;width: 300px;height: 300px;position:relative;}.son{background-color: blueviolet;height: 100px;width: 100px;position:absolute;top:50%;left:50%;margin-top:-50px;/*自身的一半*/margin-left:-50px;}2.使用position + margin垂直水平居中
非常常用的一種方法
.father{background-color:lightblue;width: 300px;height: 300px;position:relative;} .son{background-color: blueviolet;height: 100px;width: 100px;position:absolute;top:0px;left:0px;right:0px;bottom:0px;margin:auto;}3.使用flex + margin垂直水平居中
.father{background-color:lightblue;width: 300px;height: 300px;display:flex;}.son{background-color: blueviolet;height: 100px;width: 100px;margin:auto;}4.使用flex+ justify-content或align-items垂直水平居中
注意:justify-content、align-items 為css3新布局方式,注意瀏覽器的兼容性。
IE9及IE9以下不兼容
.father {background-color: lightblue;width: 300px;height: 300px;display: flex;justify-content: center;/*設置水平方向*/align-items: center;/*設置垂直方向*/}.son {background-color: blueviolet;height: 100px;width: 100px; }5.使用position定位 + transform垂直水平居中
注意:transform為 css3 新布局方式,注意瀏覽器的兼容性。
.father {background-color: lightblue;width: 300px;height: 300px;position:relative;}.son {background-color: blueviolet;height: 100px;width: 100px;position: absolute;top:50%;left: 50%;transform:translate(-50%, -50%); }6.利用table-cell垂直水平居中
.father {background-color: lightblue;width: 300px;height: 300px;vertical-align: middle;display: table-cell;text-align: center;}.son {background-color: blueviolet;height: 100px;width: 100px;display:inline-block}7.補充:使用行內塊 + text-align 水平居中
.father {background-color: lightblue;width: 300px;height: 300px;text-align: center;}.son {background-color: blueviolet;height: 100px;width: 100px;display: inline-block;}總結
- 上一篇: 企业微信消息推送卡片按钮互动的使用
- 下一篇: adlds文件服务器,window_Wi