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