在CSS中将响应宽度分为4列

时间:2019-09-28 19:02:44

标签: css response

我使用响应式界面,想将下面的代码分成4列width: 25%;,但我只实现了3列。如何将其修复为4列并仍然使用margin: 5px;

演示:https://jsfiddle.net/4je2y9nb/

    .list {
  width:100%;
  display: block;
}
.item {
    position: relative;
    width: 25%;
    height: 148px;
    font-size: 12px;
    overflow: hidden;
    background-color: red;
    float: left;
    margin: 5px;
}
<div class="list">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    </div>  
 

1 个答案:

答案 0 :(得分:1)

  

想将下面的代码分成4列宽度:25%;但我只获得了3列

指定元素的宽度时,必须考虑给定的margin属性

根据您的情况:width: calc(100% / 4 - 10px);

结果

.list {
  width: 100%;
  display: block;
}

.item {
  position: relative;
  width: calc(100% / 4 - 10px);
  height: 148px;
  font-size: 12px;
  overflow: hidden;
  background-color: red;
  float: left;
  margin: 5px;
}
<div class="list">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
</div>

还有JSFiddle

上的相同代码

enter image description here