【问题标题】:CSS property to fill parent div with image, centered, and change size to fill parent用图像填充父 div 的 CSS 属性,居中,并更改大小以填充父级
【发布时间】:2018-04-21 16:39:40
【问题描述】:

我有以下网站,其中一个随浏览器大小动态缩放的父 div 包含一个带有图像的子 div。想要的效果如下:https://shibori-demo.squarespace.com/workshops-shibori/

我的pug代码如下:

article.eventlist-event.eventlist-event--upcoming.eventlist-event--hasimg.eventlist-hasimg.eventlist-event--multiday
    a.eventlist-column-thumbnail.content-fill(href=`${link}`)


        img(src=`${img_src}`, alt=`${img_src}`
           , style='position: static; float:left; width: 100%; object-fit: contain'
           )

这段代码实现如下效果(父div为红色为效果):https://lingxiaoling-1.appspot.com/code.

一些例子:

总之,我希望图像是: 1.相对于父div居中 2.根据父div的大小调整大小,使其填满父div 3.不溢出父div。

【问题讨论】:

    标签: javascript html css responsive-design pug


    【解决方案1】:

    有几个解决方案。

    a) 使其工作的最简单方法是使用backgrund-image 而不是img 标签:

    .image {
      background-image: url(url-to-image);
      background-size: cover;
    }
    

    b) 如果图像比例始终相同,则可以使用img

    .parent {
      position: relative;
    }
    
    .img {
      position: absolute;
      height: 100%;
      width: auto;
      top: 0;
      left: 0 // or if you want to center it left: 50%; transform: translateX(-50%)
    }
    

    c) 或者您可以使父级的宽高比与父级相同:

    .parent {
      width: 100%;
      height: 0;
      padding-top: cacl(100% * (width of pic / height of pix));
      position: relative;
    }
    
    .img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }
    

    可能还有很多其他的。 我无法进入你的网站,而且你没有提供足够的标记和样式来重现确切的问题,所以我可以从你上面写的内容中推荐这一切。

    如果这两种解决方案都不能解决您的问题,您需要发布更多标记和 css 以获得帮助。

    【讨论】:

    • 这就是我通常所做的,但有时在使用模板或使用 CMS 系统时,不值得更改 HTML 结构。当父元素是固定大小时,如何使图像适合其父元素?
    猜你喜欢
    • 2014-04-25
    • 2015-07-08
    • 1970-01-01
    • 2019-11-14
    • 2020-07-12
    • 2021-09-07
    • 1970-01-01
    • 2018-12-26
    • 2015-02-15
    相关资源
    最近更新 更多