标签:ems 图片 pat vertica ima viewport relative otto htm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>垂直居中</title> <style type="text/css"> body{ background: #ccc; } #parent{ border: 1px solid blue; height: 400px; width:600px; position: relative; } #container { position: absolute; top: 0; bottom: 0; left:0; right:0; margin: auto; height: 200px; width:300px; border: 1px solid red; /*width: 70%;*/ } </style> </head> <body> <div id="parent"> <div id="container"> <p>我要用绝对定位水平垂直居中</p> <p>我要用绝对定位水平垂直居中</p> <p>我要用绝对定位水平垂直居中</p> </div> </div> </body> </html>
父元素设置为:position: relative;
子元素设置为:position: absolute;
距上50%,据左50%,然后减去元素自身宽度的距离就可以实现 top:50%;left:50%;margin:-height/2 0 0 -width/2;
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>定宽块状元素水平居中</title> <style> body{ background: #ccc; } div{ position: relative; height: 400px; width:400px; border:1px solid blue; } p{ position: absolute; top: 50%; left:50%; height: 200px; width:200px; margin: -100px 0 0 -100px; border:1px solid red; } </style> </head> <body> <div><p>我是定宽块状元素,我要垂直水平居中显示。</p></div> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>垂直居中</title> <style type="text/css"> body{ background:#ccc; } #wrapper { display: table; /*here*/ border:1px solid yellow; } #container { display: table-cell; /*here*/ vertical-align: middle; /*here*/ text-align: center; height:200px; width:300px; border:1px solid red; } </style> </head> <body> <div id="wrapper"> <div id="container"> <p>我要用表格属性垂直水平居中</p> <p>我要用表格属性垂直水平居中</p> <p>我要用表格属性垂直水平居中</p> </div> </div> </body> </html>
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>定宽块状元素水平居中</title> <style> body{ background: #ccc; } div{ height: 400px; width:400px; border:1px solid red; display:flex; justify-content: center; align-items: center; } p{ height:100px; width:100px; border:1px solid blue; } </style> </head> <body> <div><p>我是定宽块状元素,我要垂直水平居中显示。</p></div> </body> </html>
标签:ems 图片 pat vertica ima viewport relative otto htm
原文地址:https://www.cnblogs.com/sunmarvell/p/9413365.html