jQuery —设置子项以填充父项的剩余宽度

时间:2018-08-15 12:59:27

标签: javascript jquery html css

我正在建立一个响应式布局。我想知道是否有人通过JS / jQuery知道只有当有空间要填充时(右边),我才能设置子级来填充父级的剩余空间。

大于900像素时的布局

above 900px

低于900像素时的布局

enter image description here

HTML供参考

.row {
  width: 100%;
}

.colm-span-2 {
  position: relative;
  float: left;
  margin: 15px auto;
  padding: 0px 15px 0px 15px;
  background-color: #FFFFFF;
  background-clip: content-box;
}

.colm-span-2 {
  width: 33.3333333333%;
}

@media screen and (max-width: 900px) {
  .colm-span-2 {
    width: 50%;
  }
}
<div class="row">
  <div class="colm-span-2">
    <div class="bg-white">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
  <div class="colm-span-2">
    <div class="bg-cta-green">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
  <div class="colm-span-2">
    <div class="bg-dark-purple">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

我建议添加:

/tmp

到您的媒体查询。这样会将最终的.colm-span-2:last-child { width: 100%; } 更改为100%的宽度。

答案 1 :(得分:1)

使用flexbox和:last-child(假设您有行),这是可能的

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

 ::before,
 ::after {
  box-sizing: inherit;
}

.bg-white {
  background: whitesmoke;
}

.bg-cta-green {
  background: green;
}

.bg-dark-purple {
  background: rebeccapurple;
}

.row {
  display: flex;
}

.colm-span-2 {
  flex: 0 0 33%;
  margin: .25em;
  border: 1px solid grey;
}

.colm-span-2:last-child {
  flex: 1;
}
<div class="row">
  <div class="colm-span-2">
    <div class="bg-white">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
</div>


<div class="row">
  <div class="colm-span-2">
    <div class="bg-white">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
  <div class="colm-span-2">
    <div class="bg-cta-green">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
  <div class="colm-span-2">
    <div class="bg-dark-purple">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="colm-span-2">
    <div class="bg-white">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
  <div class="colm-span-2">
    <div class="bg-cta-green">
      <div class="cont-span-1">
        <h2>Test</h2>
        <p>Lorem ipsum</p>
      </div>
    </div>
  </div>
</div>