方案一:
使用inline-block
与伪类
1 2 3 4 5 6 7 8 9 10 11 12 13
| <style> *{margin:0;padding:0;} .g-popup-wrap{display:block;position:fixed;top:0;left:0;width:100%;height:100%;z-index:1501;text-align: center;} .g-popup-box{border:1px solid #ddd;background-color:#fff;display:inline-block;vertical-align:middle;text-align:left;color:#333;position:relative;} .g-popup-wrap:after{content: " ";width: 0;height: 100%;display: inline-block;vertical-align: middle;} </style> <div class="g-popup-wrap"> <div class="g-popup-box">
<p style="text-align: center;padding:30px 100px;">测试数据</p>
</div> </div>
|
方案二:
使用table-cell与vertical-align
1 2 3 4 5 6 7 8 9 10 11
| <style> .g-popup-wrap{display: table;position:fixed;top:0;left:0;width:100%;height:100%;} .box{display: table-cell;vertical-align: middle;text-align: center;} </style> <div class="g-popup-wrap"> <div class="box"> <div style="border:1px solid blue;display:inline-block;">行内块元素不定宽高</div> <div style="border:1px solid red; width:300px;margin:auto;">块元素定宽</div> <span style="border:1px solid #ff00ff;">行内素元素</span> </div> </div>
|
方案三:
fixed/absolute定位定宽定高
1 2 3 4 5 6 7
| <style> *{margin:0;padding:0;} .g-popup-wrap{position:absolute;top:0;right:0;bottom:0;left:0;margin:auto;width:200px;height:200px;border:1px solid #ddd;} </style> <div class="g-popup-wrap"> fixed/absolute定位定宽定高 </div>
|
方案四
定位于transform
不定宽不定高
1 2 3 4 5 6 7
| <style> *{margin:0;padding:0;} .g-popup-wrap{position: fixed;top:50%;left:50%;transform:translate(-50%,-50%);text-align: center;border:1px solid red;} </style> <div class="g-popup-wrap"> (fixed/absolute)与transform不定宽不定高 </div>
|
方案五
使用flex
1 2 3 4 5 6 7 8
| <style> *{margin:0;padding:0;} .g-popup-wrap{display:flex;align-items: center;justify-content: center;width:100%;height:100%;position:fixed;} .box{border:1px solid red;} </style> <div class="g-popup-wrap"> <div class="box">不定宽不定高</div> </div>
|
方案六
宽高取一半负值
1 2 3 4 5 6 7
| <style> *{margin:0;padding:0;} .g-popup-wrap{position:fixed;top:50%;left:50%;width:100px;height:100px;margin-left:-50px;margin-top:-50px;border:1px solid red;} </style> <div class="g-popup-wrap"> <div>定宽定高</div> </div>
|
方案七
使用grid
1 2 3 4 5 6 7 8 9 10 11 12
|
<style> *{margin:0;padding:0;} .g-popup-wrap{display: grid;position:fixed;width:100%;height:100%;grid-template-columns: repeat(3, 1fr);grid-template-rows: repeat(3, 1fr);} .box{grid-column: 2 / 2;grid-row: 2 / 2;border:1px solid red;} </style> <div class="g-popup-wrap"> <div class="box">宽高依赖父级grid</div> </div>
|