堆叠并排而不使用浮动左侧

时间:2016-02-02 11:19:14

标签: html css css3

我希望在不使用divs的情况下将divs宽度并排50%(2 float:left)堆叠起来,因为它将div从正常流程中取出。由于浏览器支持有限,Flexbox也不是首选。如何在不改变宽度的情况下获得所需的视图?

我的代码

*, *:before, *:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  -o-box-sizing: border-box;
  box-sizing: border-box;
}

.col {
  display: inline-block;
  width: 50%;
}

.col-content {
  padding: 0.5em;
  background-color: #ddd;
  border: 1px solid #aaa;
  color: #333;
}
<div class="container">
  <div class="col">
    <p class="col-content">
      col Item 1
    </p>
  </div>
 
  <div class="col">
    <p class="col-content">
      col Item 2
    </p>
  </div>
  
  <div class="col">
    <p class="col-content">
      col Item 3
    </p>
  </div>
 
  <div class="col">
    <p class="col-content">
      col Item 4
    </p>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

奇怪但真实 - 您可以从HTML中删除元素之间的空格 - 如下所示:

*,
*:before,
*:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  -o-box-sizing: border-box;
  box-sizing: border-box;
}
.col {
  display: inline-block;
  width: 50%;
}
.col-content {
  padding: 0.5em;
  background-color: #ddd;
  border: 1px solid #aaa;
  color: #333;
}
<div class="container">
  <div class="col">
    <p class="col-content">
      col Item 1
    </p>
  </div><!--
 
  --><div class="col">
    <p class="col-content">
      col Item 2
    </p>
  </div><!--
  
   --><div class="col">
    <p class="col-content">
      col Item 3
    </p>
  </div><!--
 
   --><div class="col">
    <p class="col-content">
      col Item 4
    </p>
  </div>
</div>

您还可以在每个内联块元素上尝试-4px的边距

答案 1 :(得分:0)

删除col div结束标记和起始标记之间的空格。

例如:

<div class="col">
    <p class="col-content">
      col Item 1
    </p>
</div>
<div class="col">
    <p class="col-content">
      col Item 2
    </p>
</div>

<div class="col">
    <p class="col-content">
      col Item 1
    </p>
</div><div class="col">
    <p class="col-content">
      col Item 2
    </p>
</div>

试试这个代码:

&#13;
&#13;
*, *:before, *:after {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  -o-box-sizing: border-box;
  box-sizing: border-box;
}

.col {
  display: inline-block;
  width: 50%;
}

.col-content {
  padding: 0.5em;
  background-color: #ddd;
  border: 1px solid #aaa;
  color: #333;
}
&#13;
<div class="container">
  <div class="col">
    <p class="col-content">
      col Item 1
    </p>
  </div><div class="col">
    <p class="col-content">
      col Item 2
    </p>
  </div><div class="col">
    <p class="col-content">
      col Item 3
    </p>
  </div><div class="col">
    <p class="col-content">
      col Item 4
    </p>
  </div>
</div>
&#13;
&#13;
&#13;