css-垂直居中多种解决方式

来源:互联网 发布:2017年时代网络诗人奖 编辑:程序博客网 时间:2024/06/16 21:36


这里总结了四种方式:


<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta charset="utf-8"> <title>CSS</title> <style>body,h1,h2,h3,h4,h5,h6,hr,menu,p,blockquote,ol,ul,dl,dd,td,th,figure,pre,button,input,textarea{margin:0 auto;padding:0;}body{font: normal 100% "微软雅黑";color:#000;font-size:14px;width:100%;background-color:#f1f2f7;}section {margin: 0 auto;position:relative;width:500px;height:400px;}.bg-color-a{background-color:honeydew;}.bg-color-b{background-color:yellowgreen;}.bg-color-c{background-color:lightyellow;}.bg-color-d{background-color:ghostwhite;}.my-div {width:400px;height:200px;border:1px solid #00F;}/*方式一、绝对定位 position: absolute;left:50%;top:50%;margin-left:-200px;margin-top:-100px;*/.center-1 {position: absolute;left:50%;/*外框 x轴 移到中心点*/top:50%; /*外框 y轴 移到中心点*/margin-left:-200px;/* x轴减width/2 */margin-top:-100px;/* y轴减height/2 */text-align: center;/*内容x轴居中*/line-height: 200px;/*内容y轴居中*/} /*方式二、 相对定位 position: relative; margin: 0 auto; top:50%; transform:translateY(-50%); */.center-2 {position: relative;margin: 0 auto;/*外框 x轴左右居中*/top:50%;/*外框 y轴垂直居中 到中心点*/transform:translateY(-50%);/*外框 y轴 垂直上移自身高度的50% */text-align: center;/*内容x轴居中*/line-height: 200px;/*内容y轴居中*/}/*方式三、 绝对定位 position: absolute; top:50%;left:50%; transform:translate(-50%,-50%); */.center-3 {position: absolute;top:50%;/*外框 y垂直居中 到中心点*/left:50%;/*外框 x垂直居中 到中心点*/transform: translate(-50%, -50%);/*外框 垂直上移自身高度的50%,左移自身高度的50% */text-align: center;/*内容x轴居中*/line-height: 200px;/*内容y轴居中*/}/*方式四、 display:flex; */.center-4 {display:flex;justify-content:center;/*外框与内容x轴垂直居中*/align-items: center;/*外框与内容y轴垂直居中*/flex-wrap: wrap; /*align-content:center;多行整体效果时使用*/text-align: center;/*内容有多行时x轴居中*/margin: 0 auto;}</style></head><body><!--方式一、绝对定位 position: absolute;left:50%;top:50%;margin-left:-200px;margin-top:-100px;--><section class="bg-color-a"><div class="my-div center-1">我要垂直居中1</div></section><hr/><!--方式二、相对定位 position: relative; margin: 0 auto; top:50%; transform:translateY(-50%);--><section class="bg-color-b"><div class="my-div center-2">我要垂直居中2</div></section><hr/><!--方式三、绝对定位 position: absolute; top:50%;left:50%; transform:translate(-50%,-50%);--><section class="bg-color-a"><div class="my-div center-3">我要垂直居中3</div></section><hr/><!--方式四、display:flex;--><section class="bg-color-b center-4"><div class="my-div center-4"><div style="padding:15px;background-color:gold;">我要垂直居中4<br>啊啊啊啊啊啊啊啊</div><div style="padding:15px;background-color:goldenrod;">我要垂直居中4</div><div style="padding:15px;background-color:gray;">我要垂直居中4</div><div style="padding:15px;background-color:gold;">我要垂直居中4<br>啊啊啊啊啊啊啊啊</div><div style="padding:15px;background-color:goldenrod;">我要垂直居中4</div><div style="padding:15px;background-color:gray;">我要垂直居中4</div></div></section><hr/></body></html>


如图:






原创粉丝点击