图像不会拉伸容器宽度

时间:2013-07-29 22:35:43

标签: css image responsive-design

我无法获取图像来拉伸包含元素的整个宽度。页面布局是双列流体响应。主要内容包含在左栏中,而“额外”的内容包含在右栏中。我创建了一个400x400的图像,我希望它出现在最右侧的右侧边栏(class = "top-sidebar")中。我不能为我的生活得到图像,以适应其宽度与顶部侧边栏的宽度。这是我的代码片段:

HTML:

<aside class="top-sidebar">
        <article>
            <p><img src="images/callustoday.jpg" alt="Call us today at 716-200-7397 to start training!"/></p>
        </article>
    </aside>

相应的CSS:

.top-sidebar {
    width: 22%;
    float: left;
    background-color: #efefef;
    border-radius: 5px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    margin: 2% 0 0 2%;
    padding: 0;
}

.top-sidebar img {
    max-width: 100%;
    margin: 0 auto;
    height: auto;
    display: block;
}

为了增加挫败感,我甚至无法使用margin-left: automargin-right: auto

让图片在其父容器中居中

3 个答案:

答案 0 :(得分:1)

对于后一部分: 如果应用样式的块元素具有以像素为单位的已定义宽度,则使用margin: auto仅适用于居中。例如,如果您为图像指定宽度为300像素,则它将居中。由于这不是一个选项,我建议采用不同的方法:

如何将图片background-image放在article标记上? 这样,您可以使用background-position: center使图像居中,并使用background-size: cover

使其跨越整个宽度

可以找到解决方案here

HTML:

<aside class="top-sidebar">
    <article class="callustoday">
    </article>
</aside>

CSS:

.callustoday{
    background-image: url("yourimage.png");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    width: 100%;
    height: 100%;
}

.top-sidebar {
    width: 22%;
    height: 100px;
    float: left;
    background-color: #efefef;
    border-radius: 5px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    margin: 2% 0 0 2%;
    padding: 0;
}

答案 1 :(得分:1)

.callustoday {
    background-image: url(yourimage.png);
    background-size: cover;
    background-repeat: no-repeat;
    width: 100%;
    height: 100%;
}

您应该查看border: 1px red solid;以查看包含图片的盒子有多大;这样,你总能看到发生了什么。

答案 2 :(得分:0)

使用浏览器缩放图像是不好的做法,因为它往往会产生额外的开销(不必要的大文件大小/分辨率),或者糟糕的用户体验(由于放大或不正确的宽高比而导致的像素化低分辨率图像)

话虽如此,您只需在CSS中设置max-width img。您是否尝试过设置width: 100%?如果这不起作用,请尝试将float: left;添加到.top-sidebar img