双边框 div 应该合并 css



如果你看这个小提琴,你会发现边界不会合并。
.css:

div{
    float:left;
    background-color:moccasin;
    width:100px;
    height:100px;
    border:1px solid tomato;
}

div 的数量是随机的,我只能给它 1 个类/ID。
另请记住,页面可以调整大小,并且一行上的div 数量可以更改。

我已经尝试了margin-left:1px;和最后一个子/n个子()选择器,但是当您调整屏幕大小时它们不起作用,或者它仍然会给出不需要的边框。

编辑:我不能移动单个像素的div,当我给div margin-left:-1px;并给出第一个div margin-left:1px;我会在接下来的行中得到不需要的结果。

只需添加到div

margin-top: -1px;
margin-left: -1px;

检查以下示例:

div{
    float:left;
    background-color:moccasin;
    width:100px;
    height:100px;
    border:1px solid tomato;
    margin-left: -1px;
    margin-top: -1px;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

使用 JS 的另一种解决方案这是演示

.CSS:

div{
float:left;
background-color:moccasin;
width:100px;
height:100px;    
border-bottom:1px solid tomato;
border-right:1px solid tomato;
}
div:first-child{
border-left:1px solid tomato;
}
div.first-row {
border-top: 1px solid tomato;
}

j查询:

var borderCollapse = function() {
var div = $('div');
var divWidth = 0;
var rows = 1;
div.each(function() {
var that = $(this);
var div = $('div');
var width = div.parent().width();
var thisWidth = $(this).width();
if (divWidth < width) {    
    that.prev().not('div:first-child').css({'border-left':'0'});
    divWidth += parseInt(thisWidth);        
} else { 
    that.prev().css({'border-left':'1px solid tomato'});
    divWidth = 2 * thisWidth;
    rows += 1;        
}
if (rows <= 1) {
    that.prev().addClass('first-row');
} else {
    that.prev().removeClass('first-row');
}
});
}
borderCollapse();
$(window).resize(function() {
  borderCollapse();
});

我们可以用box-shadow: 0 0 0 1px tomato而不是边框来模拟折叠的边框; 添加 1px 的左边距和下边距以正确对齐。

这是有效的,因为盒子阴影自然是重叠的;它本身不占用空间。我们仅显示具有左边距和下边距的所需阴影量。

带有 1px 的"边框"

div {
  float: left;
  background-color: moccasin;
  width: 100px;
  height: 100px;
  box-shadow: 0 0 0 1px tomato;
  margin: 0 0 1px 1px; 
 /* the margin provides a little nudge as 
 box shadow won't take up space like a border 
 */
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

带有 5px 的"边框"

div {
  float: left;
  background-color: moccasin;
  width: 100px;
  height: 100px;
  box-shadow: 0 0 0 5px tomato;
  margin: 0 0 5px 5px; 
 /* the margin provides a little nudge as 
 box shadow won't take up space like a border 
 */
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

最新更新