元素水平垂直居中
一、脫離文檔流元素的居中
只可用于定寬高元素;
方法一:margin:auto法
<!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>方法二:負margin法
父元素設置為:position: relative;?
子元素設置為:position: absolute;
距上50%,據左50%,然后減去元素自身寬度的距離就可以實現?top:50%;left:50%;margin:-height/2 0 0 -width/2;
方法三:transform?
定寬高和不定寬高元素皆可;
用法:
#child {position: absolute;top: 50%;left:50%;transform: translate(-50%,-50%);/* height: 200px;width:300px;*/border: 1px solid red;} <!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: 50%;left:50%;transform: translate(-50%,-50%);/* height: 200px;width:300px;*/border: 1px solid red;} </style> </head><body><div id="parent"><div id="container"><p>我要用絕對定位水平垂直居中</p><p>我要用絕對定位水平垂直居中</p><p>我要用絕對定位水平垂直居中</p></div></div></body> </html>二、未脫離文檔流元素的居中
方法一:table-cell法
有一定的bug,父元素會和子元素一般大,但是確實居中了;
定寬高和不定寬高元素皆可;
<!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>方法二:flex布局
定寬高和不定寬高元素皆可;
<!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>?
轉載于:https://www.cnblogs.com/sunmarvell/p/9413365.html
總結
- 上一篇: ubuntu将GNU nano换成vim
- 下一篇: 开始一个新项目