【问题标题】:Images auto fill container div no matter the number of images无论图像数量如何,图像都会自动填充容器 div
【发布时间】:2014-03-27 01:07:47
【问题描述】:

我想创建一个容器 div 并向其中添加“X”数量的图像。但无论里面有多少图片,它们总是会均匀地填满整个容器。

为了便于理解,这里有一张图片:

最好只使用 HTML/CSS,但我当然愿意接受其他想法。在这方面有点新,所以任何帮助都会很棒。

【问题讨论】:

    标签: html css image responsive-design


    【解决方案1】:

    您可以使用 CSS 来做到这一点。诀窍是使用width:50%; 制作图像float:left;。如果最后一张图像恰好是奇数图像,那么我们需要将其设为全宽。这是使用选择器img:last-child:nth-child(odd) 完成的。

    这是图片的完整 CSS:

    CSS

    img {
        float:left;
        width:50%;
    }
    
    /*
    * This makes the last image (if odd)
    * full width.
    */
    img:last-child:nth-child(odd) {
        width:100%;
    }
    
    /*
     Special rules for 2 images
    */
    
    div.container > img:first-child:nth-last-child(2) {
        width:100%;
    }
    
    div.container > img:last-child:nth-child(2) {
        width:100%;
    }
    

    这是完整的demo

    【讨论】:

    • 非常感谢! 100% 是我想要的。
    猜你喜欢
    • 2015-10-29
    • 1970-01-01
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2016-05-30
    相关资源
    最近更新 更多