css当图⽚宽度为百分⽐,⾼度如何按宽度⽐例展⽰
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.main{
width:300px;
height:300px;
padding:10px;
background-color: #0087F1;
margin:10px;
float: left;
}
.imgbox1 {
position: relative;
/* 下⾯为css处理办法 */
content: '';
width: 100%;
padding-top: 100%;
display: block;
}
.imgbox2 {
position: relative;
/* 下⾯为css处理办法 */
content: '';
width: 100%;
padding-top: 70%;
display: block;
}
.imgbox3 {
position: relative;
/
* 下⾯为css处理办法 */
margin属性值可以为百分比content: '';
width: 80%;
padding-top: 50%;
display: block;
}
img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<!-- 宽度占容器百分之百,⾼度和宽度⼀⽐⼀ -->
<div class="main">
<div class="imgbox1">
<img src="gimg2.baidu/image_search/src=http%3A%2F%l-img%2Ft_s640x2000%2Fg5%2FM00%2F03%2F0D%2FC hMkJlawkneIQL3lAARnfQ9pCogAAIOSAPcT2AABGeV555.jpg&refer=http%3A%2F%l-img&app=2002&size=f9999,10000&q=a80&n=0 &g=0n&fmt=jpeg?sec=1614742344&t=8fed9d197f990c15c4bd191a5726a379">
</div>
</div>
<!-- 宽度占容器百分之百,⾼度为宽度百分之七⼗ 10:7-->
<div class="main">
<div class="imgbox2">
<div class="imgbox2">
<img src="gimg2.baidu/image_search/src=http%3A%2F%l-img%2Ft_s640x2000%2Fg5%2FM00%2F03%2F0D%2FCh MkJlawkneIQL3lAARnfQ9pCogAAIOSAPcT2AABGeV555.jpg&refer=http%3A%2F%l-img&app=2002&size=f9999,10000&q=a80&n=0 &g=0n&fmt=jpeg?sec=1614742344&t=8fed9d197f990c15c4bd191a5726a379">
</div>
</div>
<!-- 宽度占容器百分之⼋⼗,⾼度占宽度百分之五⼗宽⾼8:5 -->
<div class="main">
<div class="imgbox3">
<img src="gimg2.baidu/image_search/src=http%3A%2F%l-img%2Ft_s640x2000%2Fg5%2FM00%2F03%2F0D%2FCh MkJlawkneIQL3lAARnfQ9pCogAAIOSAPcT2AABGeV555.jpg&refer=http%3A%2F%l-img&app=2002&size=f9999,10000&q=a80&n=0 &g=0n&fmt=jpeg?sec=1614742344&t=8fed9d197f990c15c4bd191a5726a379">
</div>
</div>
</body>
</html>
⽅法原理是给imgbox⼀个padding-top,撑开容器,撑开的⾼度是按照盒⼦宽度(百分⽐)等⽐撑开,最后把img放进去填满盒⼦就可以了。
这可以解决写死图⽚存放区,⽆论后台传过来什么样的图⽚,前端都可以在给定⼤⼩盒⼦⾥放图⽚,且是按⽐例存放的,不过这样也会出现图⽚被压缩的问题。
也可以⽤js⽅法解决
//调⽤
doSomeThing('img');
//函数
function doSomeThing(myClassName){
var aDiv = ElementsByTagName('img');
for(var i = 0; i < aDiv.length; i++){
if(aDiv[i].className == myClassName){
aDiv[i].style.height = aDiv[i].offsetWidth * 0.8 + 'px';
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论