无法在容器内均匀定位图像

时间:2015-02-15 10:01:32

标签: html css image

关于将浮动应用于可调整大小的图像的一个问题由Gasim(谢谢你)回答,但我还有一个问题要解决。

我有两张图片已经应用了这个css代码......

.image-container {
display: inline-block;
width: 100%;
background-size: cover;
background-position: center;
background-image: url(Images/Filler2.png);
height: 250px;
margin-right: auto;
margin-left: auto;
}

@media only screen and (min-width : 1200px) {
.image-container {
    max-width: 500px;
}
}

.image-container2 {
display: inline-block;
width: 100%;
background-size: cover;
background-position: center;
background-image: url(Images/Filler3.png);
height: 250px;
margin-right: auto;
margin-left: auto;
}

@media only screen and (min-width : 1200px) {
.image-container2 {
    max-width: 500px;
}
}

所以现在他们正确地调整大小并且彼此对齐,我无法像下面的例子那样水平放置它们。我尝试了唯一的方法,我知道如何做到这一点(margin-left:auto,margin-right:auto)但这不起作用。填充也不起作用?这段代码中是否有一部分可以阻止这两者的工作,如果有的话,我需要修复它? 任何有用的输入,谢谢:)

http://imageshack.com/a/img912/981/MBjvwx.png

1 个答案:

答案 0 :(得分:1)

也许这不是响应式图像的最佳解决方案,但我通常使用移动第一种方法进行媒体查询,并且效果很好。基本上,默认情况下,您将框的宽度设置为100%,在较大的屏幕上,您可以设置所需的宽度:

.image-container {
    float: left;
    width: 100%;
    background-size: cover;
    background-position: center center;
    background-color: red; /* for testing */
    height: 250px;
}

@media only screen and (min-width : 1224px) {
    .image-container {
        max-width: 500px;
    }
}

结果如下:http://codepen.io/gasim/pen/xbYQdd

尝试使窗口尺寸更小,您将看到差异。测试,调试和修改此代码要简单得多。

编辑:忘了提。如果您也可以使用display: inline-block而不是浮点数。

编辑2:要在容器之间添加填充,您需要为特定值添加边距,而不是自动。例如:

.image-container {
   /* rest of the values */
   margin: 5px;
}

这将为图像容器的左,右,顶部和底部添加5px边距。如果你想让图像容器居中,我会将它们添加到另一个容器中:

<div class="container">
   <div class="image-container" style="background-image: url(URL_HERE);"></div>
   <div class="image-container" style="background-image: url(URL_HERE);"></div>
</div>

并添加样式:

 @media only screen and (min-width: 1224px) {
     .container {
        width: 80%;
        margin: 0 auto;
     }
 }

另外,请查看我添加背景图片的方式,使用样式。它比为每个背景图像编写CSS要清晰得多。这样你就可以拥有一个类image-container,只需添加尽可能多的背景图像,而不依赖于CSS。

相关问题