css - 根据容器宽度调整间隙或图像的大小

时间:2016-01-31 15:03:20

标签: css alignment multiple-columns

我正在尝试创建一个简单的响应式图库,其默认列数为3.随着窗口宽度变小,列数也应减少(首先减少到2,最后减少到1)。

现有代码工作正常,但是当图像重新排列为2列时,它们会向左对齐,在#container的右侧留下一个丑陋的空间。

如何动态增加图像之间的间隙,使图像仍然在#container上拉伸,使#container中的所有内容保持水平对称?任何人都可以帮助我。

我尝试了一些明显的候选人(例如#gallery img {align:center}但没有一个能够奏效。

解决方案/提示可以是css / sass和/或js。

<div id="container">
  <header><h1>My Gallery</h1></header>
  <div id="filter"></div>
  <div id="gallery">
        <img src="http://lorempixel.com/400/200/" alt="Gal" />
        <img src="http://lorempixel.com/400/200/" alt="Gal" />
        <img src="http://lorempixel.com/400/200/" alt="ggg" />
        <img src="http://lorempixel.com/400/200/" alt="gog" />
        <img src="http://lorempixel.com/400/200/" alt="Gallery" />
        <img src="http://lorempixel.com/400/200/" alt="Gallery" />
</div> <!-- end of gallery-->
</div> <!-- end of container -->

CSS:

#container {
  width: 70%;
  margin: 0 auto;
  background-color: gray;
  }

2 个答案:

答案 0 :(得分:1)

只需将此代码添加到CSS部分

即可
#gallery{ text-align: center;}

答案 1 :(得分:1)

enter image description here enter image description here

HTML:

  <div id="container">
      <header><h1>My Gallery</h1></header>
      <div id="filter"></div>
      <ul id="gallery">
         <li>
            <img src="http://lorempixel.com/400/200/" alt="Gal" />
         </li>
         <li>
            <img src="http://lorempixel.com/400/200/" alt="Gal" />
         </li>
         <li>
            <img src="http://lorempixel.com/400/200/" alt="Gal" />
         </li>
         <li>
            <img src="http://lorempixel.com/400/200/" alt="Gal" />
         </li>
    </ul> <!-- end of gallery-->
    </div> <!-- end of container -->

的CSS:

    #container {
      width: 70%;
      margin: 0 auto;
      background-color: gray;
      }
    #gallery{
      width:100%;
      list-style:none;
      clear:both;
       margin:0;
       padding:0;
    }
#gallery:before,
#gallery:after{
    content: " ";
    display: table;
    clear: both;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}
    #gallery li{
       margin:0;
       width:23.3333%;
       height:auto;
       display:block;
       float:left;
    }
    #gallery li img{
       display:block;
       margin: 0 auto;
       width:100%;
       max-width:100%;
    }

Codepen

上进行测试
相关问题