响应显示百分比div内的图像

时间:2015-04-21 04:26:20

标签: html css html5 css3

我一直在努力寻找答案。当我调整百分比div元素窗口的大小时,是否有任何可能的方法来显示图像元素?

CSS

div{
    width:60%;
    height:400px;
}
div > img{
    width:100%;
    height:100%;
    min-height:100%;
    min-width:100%;
    background:tomato
}

HTML

<div>
    <img src="" alt="" />
</div>

Fiddle

谢谢

6 个答案:

答案 0 :(得分:0)

使用以下代码替换您的样式,然后尝试。

div > img {
  width: 100%;
  background: tomato;
}

答案 1 :(得分:0)

你可以用媒体查询设置不同的高度和宽度设备的不同高度和宽度像跟随

    @media screen and (max-width: 300px) {
        div {
            width:60%;
            height:150px;
        }
        img{
            width:60%;
            height:150px;
        }
    }
 @media screen and (max-width: 768px) {
        div {
            width:70%;
            height:450px;
        }
        img{
            width:60%;
            height:300px;
        }
    }

这里为两个不同的设备或屏幕区域指定了两个不同的样式表,第一个div和图像仅适用于最小宽度为300像素的那些设备/屏幕区域,另一个适用于最小宽度为300像素的设备/屏幕区域分辨率为768px

有关mediaquery的更多信息,请点击链接 http://www.w3schools.com/cssref/css3_pr_mediaquery.asp

答案 2 :(得分:0)

使用max-width:100%

div > img{
    max-width:100%;
    height:100%;
    min-height:100%;
    /*min-width:100%;*/
    background:tomato
}

  div{
    width:60%;
    height:400px;
}
div > img{
    max-width:100%;
    height:100%;
    min-height:100%;
    /*min-width:100%;*/
    background:tomato;
}
<div>
    <img src="https://css-tricks.com/wp-content/csstricks-uploads/fullpagebackground.jpg" alt="" />
</div>

答案 3 :(得分:0)

CSS

div {
    height: 400px; /* or whatever value you need here */
    width: 60%;  /* or whatever value you need here */
}

div > img {
    /*  Image will scale down proportionally so 
        it will fit inside its container.
        But if the image is smaller than the container,
        Then it won't stretch to fit the container.

        Note: min-width will force the image to stretch
        You also cannot have width or height specifically set either.
    */
    max-width: 100%;
    max-height: 100%;
}

jsFiddle:http://jsfiddle.net/sxzwrmr8/4/

答案 4 :(得分:0)

如果您要做的是使高度与宽度成比例缩小,我根本不会设置任何height属性:

div > img{
    width:100%;
    min-width:100%;
    background:tomato
}

JSFiddle Here

如果您真的希望对高度有一定的控制权,我建议您使用简单的vw作为height值 - 假设父div确实占用了这样的屏幕的整个宽度。然后指定一个固定的min-height

div > img{
    width:100%;
    height:60vw;
    min-height:60px;
    min-width:60px;
    background:tomato
}

JSFiddle Here

答案 5 :(得分:0)

制作响应式网站时,最好使用最大宽度:100%

max-width:100%不允许图像的宽度超出外部div的宽度和自己的宽度,但如果您希望图像始终采用整个宽度然后使用

div img {width:100%}