目录
一、不知图片大小的情况下
1.1、方法一
.parent { position: relative; display: block; .img { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } }
1.2、方法二
.parent { display: table-cell; // width要写得大一点,以撑满容器之外部容易的宽度 width: 3000px; text-align: center; vertical-align: middle; .img { display: inline-block; vertical-align: middle; } }
1.3、方法三(如果父元素的高度为已知的定制)
.parent { display: block; text-align: center; height: 300px; line-height: 300px; .img { display: inline-block; } }
二、知道图片大小和父级元素大小的情况下
2.1、方法四(写死距离)
.parent { display: block; height: 400px; .img { display: block; height: 100px; margin: 150px auto 0; } }
2.2、方法五(写死距离)
.parent { position: relative; display: block; width: 600px; height: 400px; .img { position: absolute; width: 100px; height: 300px; top: 50px; left: 250px; } }
三、如果父级元素的尺寸可以由内部图片元素决定
3.1、方法六
.parent { display: inline-block; // 包围内部元素 .img { padding: 30px 20px; // 用来加大父元素的尺寸 } }
3.2、方法七
.parent { display: block; height: 300px; background: transparent url('./img/beauty.png') scroll no-repeat center center; background-size: 100px 200px; }
四、使用弹性盒模型
.parent { display: flex; align-items: center; justify-content: center; }