场景需求
页面实现大头贴功能,相框固定,照片可更换,类似下图。

解题思路
其实我们可以拆分一下:相框.png是一张图片,金泰熙小姐姐照片.jpg是另一张图片,只要把相框.png叠在金泰熙小姐姐照片.jpg图片前面,那么就实现啦!
先上HTML结构:
<div class="box">
<img class="photo" src="金泰熙小姐姐照片.jpg" alt="我是原始照片_宽高不定" />
<img class="phframe" src="相框.png" alt="我是花里胡哨的相框_中间镂空" />
</div>
相框为固定宽高,假设宽为300px,高为400px。
CSS样式如下:
.box{width:300px;height:400px;overflow:hidden;position:relative;}
.photo{height:400px;}
.phframe{width:300px;height:400px;position:absolute;left:0;top:0;}
那么问题来了,photo怎么居中?
试过的不成功解法:
1、把photo设为绝对定位,left:-50%,再设margin-left为负值。由于photo宽度不确定,因此margin-left具体值不确定。
2、宽度设为300px,图片变形。
3、把photo设为绝对定位,margin:auto,left:0,right:0。当box容器宽度小于photo时,该方法失效。
解决方法
以上方法均无法实现居中后,想到如下可行办法:
HTML结构:
<div class="box">
<div class="photobox">
<img class="photo" src="金泰熙小姐姐照片.jpg" alt="我是原始照片_宽高不定" />
</div>
<img class="phframe" src="相框.png" alt="我是花里胡哨的相框_中间镂空" />
</div>
CSS样式:
.box{width:300px;height:400px;overflow:hidden;position:relative;}
.photobox{width:1000px;height:400px;position:absolute;left:-350px;top:0;text-align:center;}
.photo{height:400px;}
.phframe{width:300px;height:400px;position:absolute;left:0;top:0;}
给photo外加一个div容器photobox,给photobox设定一个足够宽的宽度,再将photobox相对box居中,然后再用text-align:center让photo相对于photobox居中。
photobox容器left值=(photobox容器宽 - box容器宽)/2
网友评论