background-image height在css中适当缩小?

时间:2016-02-08 20:26:18

标签: css responsive-design background-image

我目前为我的内容构建了一个网格布局,我想使用div列中的图像作为背景。起初我在div列中放置了一个" img-responsive类的图像,这非常有效。现在我想达到相同的效果,但将图像作为背景。我无法使用div的宽度来缩放背景图像高度。对于img-responsive类,我有一个宽度:100%;'和'身高:自动;'我如何将相同的逻辑应用于背景图像?我无法将div列类设置为height:auto;或者具有N个像素的最大高度,因为它不显示任何内容。下面是我的代码示例,前两个div是我想要的背景图像。谁能向我解释我是如何实现这一目标的?



      body {
        margin: 0 auto;
        padding: 30px 30px 5px 30px;
        font-family: sans-serif;
        color: black;
        font-size: 1.2em;
      }
      section {
        width: 80%;
        margin: 0px auto;
        line-height: 1.5em;
        font-size: 0.9em;
        padding: 30px;
        color: black;
        overflow: hidden;
      }
      .row {
        margin: 1% auto;
        width: 100%;
        overflow: hidden;
        padding-bottom: 10px;
      }
      .row::after {
        content: "";
        display: table;
        clear: both;
      }
      .col {
        line-height: 0;
        margin-left: 1%;
        margin-right: 1%;
        margin-top: 1%;
        margin-bottom: 1%;
        display: inline-block;
        float: left;
        overflow: hidden;
      }
      .col:first-child {
        margin-left: 0px;
      }
      .col:last-child {
        margin-right: 0px;
      }
      .img-responsive {
        max-width: 100%;
        height: auto;
      }
      .col.col-6 {
        width: 47%;
        height: auto;
        border: 2px solid black;
        margin-left: 1%;
        margin-right: 1%;
      }
      .col.col-6-bg {
        width: 47%;
        max-height: 1000px;
        min-height: 145px;
        min-height: 200px;
        margin-left: 1%;
        margin-right: 1%;
        border: 2px solid black;
      }
      .img-bg {
        background-image: url("http://prasinostcharles.com/wp-content/uploads/2014/09/gallery-large_food_cod.jpg");
        background-size: cover;
        background-repeat: no-repeat;
        background-position: center center;
      }
      @media (max-width: 766px) {
        section {
          width: 90%;
        }
        col {
          width: 80%;
          margin: 10px auto;
          padding: 0;
        }
        .col.col-6 {
          width: 98%;
          min-height: 141px;
          margin-left: 0;
          margin-right: 0;
        }
        .col.col-6-bg {
          width: 98%;
          min-height: 200px;
          margin-left: 1%;
          margin-right: 1%;
        }
      }

<h2>Div with img</h2>
<div class="row">

  <div class="col col-6">
    <img class="img-responsive" src="http://prasinostcharles.com/wp-content/uploads/2014/09/gallery-large_food_cod.jpg">
  </div>
  <div class="col col-6">
    <img class="img-responsive" src="http://prasinostcharles.com/wp-content/uploads/2014/09/gallery-large_food_cod.jpg">
  </div>

</div>

<h2> Div with img as bacground</h2>
<div class="col col-6-bg img-bg"></div>
<div class="col col-6-bg img-bg"></div>
&#13;
&#13;
&#13;

0 个答案:

没有答案