html中的垂直居中和⽔平居中⽅法⼀:运⽤flex布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="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-self:center
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
.app{width: 500px;height: 500px;background: green;}
.app{display: flex;justify-content: center}
.app img{align-self: 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 charset="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 charset="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中的div居中
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>
⽅法五:
⽤padding
⽅法六:
height/line-height设为相同值
⽅法七:
⽗元素设置{ display: table-cell; vertical-align: middle; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="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 charset="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>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。