如何用CSS让一个容器水平垂直居中?
生活随笔
收集整理的這篇文章主要介紹了
如何用CSS让一个容器水平垂直居中?
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
- 第一類(被居中的元素有固定的寬高)
效果:
第一種方法(絕對定位 + 負(fù)margin)
2.第二種方法(絕對定位 + margin: auto)
<div class="div1"> <div class="div2"></div> </div><style type="text/css"> .div1{width: 100px;height: 100px;border: 1px solid #000000;position: relative;}.div2{width: 40px;height: 40px;background-color: green;position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin: auto;}</style>3.第三種方法(flex)
<div class="div1"> <div class="div2"></div> </div><style type="text/css"> .div1{width: 100px;height: 100px;border: 1px solid #000000;display: flex;}.div2{width: 40px;height: 40px;background-color: green;margin: auto;}</style>- 第二類(被居中的元素任意高度)
效果:
或
方法:display:table-cell:
<div class="div1"> <div class="div2">張三豐</div> </div> <style type="text/css"> .div1{width: 100px;height: 100px;border: 1px solid #000000;display: table-cell;vertical-align: middle;}.div2{width: 40px;background-color: green;margin: 0 auto;} </style>- 第三類(被居中的元素 寬高都不限制)
效果:
1.CSS3 flex
<div class="div1"> <div class="div2">小阿三</div> </div><style type="text/css"> .div1{width: 100px;height: 100px;border: 1px solid #000000;display: flex;align-items: center;justify-content: center;}.div2{background-color: green;}</style>2.transform:
<div class="div1"> <div class="div2">小阿三</div> </div><style type="text/css"> .div1{width: 100px;height: 100px;border: 1px solid #000000;position: relative;}.div2{background-color: green;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);}</style>- 第四類(讓圖片居中)
效果:
總結(jié)
以上是生活随笔為你收集整理的如何用CSS让一个容器水平垂直居中?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【linux磁盘分区--格式化】fdis
- 下一篇: cobbler工作流分析