上九天揽月
html中的垂直居中和⽔平居中⽅法⼀:运⽤flex布局
<!DOCTYPE html>
考研题目
<html lang="en">
<head>
<meta chart="utf-8">
<style>
.app{width: 500px;height: 500px;background: green;}
.app{display: flex;align-items: center;justify-content: center}
/*这样⽤text-align⽆⽤,布局以后,⼦元素的float、clear和vertical-align属性将失效。*/
.app img{width: 200px;height: 200px}
</style>
</head>
<body>
<div class='app'>
<img src="img/bg.jpg"alt="img"title="img"/>
</div>
</body>
</html>
⽅法⼆:也是运⽤flex布局,不过这次是在⼦元素⽤align-lf:center
<!DOCTYPE html>
<html lang="en">
<head>
<meta chart="utf-8">
<style>
.app{width: 500px;height: 500px;background: green;}
.app{display: flex;justify-content: center}
.app img{align-lf: center}
.app img{width: 200px;height: 200px}
</style>
</head>继续教育
<body>
<div class='app'>
<img src="img/bg.jpg"alt="img"title="img"/>
</div>
</body>
</html>
⽅法⼀和⽅法⼆的效果如图:
⽅法三:
如果在⼀段块元素包裹的⾏内元素中有某个元素⽐较特殊, ⽐如: ⼤写加粗的⽂字 、 乱⼊的图⽚图标, 垂直居中:
效果:<!DOCTYPE html>
<html lang="en">
<head>
<meta chart="utf-8">
<style>
.text{width: 500px;height: 500px;background: red;}
.text img{ width: 200px;height: 200px;vertical-align: middle;}
</style>
</head>
<body>
<div class="text">
<img src="img/bg.jpg"alt="img"title="img"/>可以的
</div>
</body>
</html>
⽅法四:
⽗元素相对定位(或其他定位){ position: relative; }
⼦元素绝对定位{ position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto }
<!DOCTYPE html>
<html lang="en">
<head>
<meta chart="utf-8">
<style>
.outer{width: 400px;height: 400px;background: pink;position: relative;}
.inner{width: 200px;height: 200px;background: black;position: absolute;left: 0;bottom: 0;top: 0;right: 0;margin: auto}
</style>
</head>
<body>
昆虫卡通图片
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>
⽅法五:
⽤padding
⽅法六:
height/line-height设为相同值
⽅法七:
⽗元素设置{ display: table-cell; vertical-align: middle; }
<!DOCTYPE html>
epma<html lang="en">
<head>
泰国清迈
<meta chart="utf-8">
<style>
.动物它的英语
app{width: 500px;height: 500px;background: green;}
.app{display: table-cell;vertical-align: middle;text-align: center}
.app img{width: 200px;height: 200px}
</style>
</head>
工作疏忽自我检讨<body>
<div class='app'>
<img src="img/bg.jpg"alt="img"title="img"/>
</div>
</body>
</html>
⽅法⼋:
⽗元素:position:relative
中间元素:position:absolute;left:50%;top:50%
⼦元素:position:absolute;left:-50%;top:-50%
<!DOCTYPE html>
<html lang="en">
<head>
<meta chart="utf-8">
<style>
.container{width: 400px;height: 400px;position: relative;background: pink}
.box{position: absolute;left:50%;top:50%;width: 200px;height: 200px}
.boxinner{width: 200px;height: 200px;position: relative;left: -50%;top:-50%;background: black}
</style>
</head>
<body>
<div class="container">
<div class="box">
<div class="boxinner"></div>
</div>
</div>
</body>
</html>