Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

图片自适应宽度且保持长宽比的实现方法 #6

Open
shiiiiiiji opened this issue Apr 2, 2018 · 2 comments
Open

图片自适应宽度且保持长宽比的实现方法 #6

shiiiiiiji opened this issue Apr 2, 2018 · 2 comments
Assignees

Comments

@shiiiiiiji
Copy link
Owner

shiiiiiiji commented Apr 2, 2018

在业务过程中,经常会收到UI这样的要求:

UI:这里的banner图后台会配置好,我们给他们固定尺寸(比例)的图片,你这里要根据保证宽度自适应,而且长宽比要保持750*180的比例。
FE:好的,没问题

可是,在实现过程中,如果设置:

img{
  width: 100%;
  height: ?
}

高度如何设置呢,24%?——不对呀,高度一般是参照父容器元素的height,宽度虽然自适应了,但是怎么让高度是参照宽度的比例来设置呀?

后来查资料过程中发现,padding属性如果给定百分比值时,是参照包含容器宽度的

The size of the padding as a percentage, relative to the width of the containing block.
参见https://developer.mozilla.org/en-US/docs/Web/CSS/padding

就可以以下面方式来实现:

.banner-item{
  width: 100%;
  height: 0;
  padding-bottom: 24%;
  background: url('https://dummyimage.com/750x180/ddd/fff') no-repeat center;
}
@shiiiiiiji shiiiiiiji self-assigned this Apr 2, 2018
@shiiiiiiji
Copy link
Owner Author

shiiiiiiji commented May 21, 2018

发现设置后如果再在其中嵌入容器正常情况下无法继承真实height,得到的高度为0,但是设置为position: absolute后就能够继承父容器的真实高度(包含padding),why?

有人说绝对定位元素是相对于定位元素的边界,具体原因待查。

@shiiiiiiji
Copy link
Owner Author

发现一篇文章比我写得好,记下来:
CSS实现宽高等比例自适应矩形

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant