4
22
2015
0

[css3]背景图片容器自适应高度

通常我们在做自适应图片的时候,会设置img标签宽度100%,高度auto

<style>
img{
    width: 100%;
}
</style>

<img src=""> 

但如果遇到是标签背景图的时候标签无法做到通过背景图片自适应撑开高度

 

我们可以利用background-size : contain;和padding-bottom来实现

<style>
div{
    background: url() no-repeat;
    background-size: contain;
    width: 100%;
    height: 0;
    padding-bottom: 100%;/*这里的取值取决于图片比例*/
}
</style>

<div></div>

 

 

这个方法的技巧点在于通过控制padding-bottom和width的比值,来控制div的显示比例

 

例:

假如图片尺寸是宽100px * 高60px

width是100%

height保持0

padding-bottom设置为60%

 

测试地址

Category: 未分类 | Tags: css3 布局 自适应 | Read Count: 7749

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com