2017-08-09 44 views
0

很难在标题中解释,所以我会详细说明。显然我明白,额外的空间不能添加在两个元素之间,相当于容器的100%宽度,但我想知道是否有办法将宽度减少40px。如何在60%+ 40%宽度的两个元素之间添加空格?

我非常有信心如果需要,我可以在JavaScript中做到这一点,但如果有更简单的css解决方案可用,我宁愿使用它。

为了进一步解释,我想一个40像素bewteen此图像中看到了两个白色的元素:https://gyazo.com/551af056aa516eac2ce3c7b16949a0fa

正如你可以看到我有一个左,右列的大型容器,40%的宽度和60%。

HTML:

<div id="homeContentContainer" class="homeContentContainer"> 

    <div class="leftCol"> 
     <div class="buyPanel panel"> 
     </div> 
     <div class="sellPanel panel"> 
     </div> 
    </div> 
    <div class="rightCol"> 
     <div class="buyPanel panel"> 
     </div> 
    </div> 

</div> <!-- content container --> 

CSS:

.homeContentContainer { 
    position: absolute; 
    width: 60%; 
    margin: 0 auto; 
    top: 70px; 
    left: 0px; 
    right: 0px; 
} 

.leftCol { 
    width: 40%; 
    height: 100%; 
    float: left; 
} 

.rightCol { 
    width: 60%; 
    height: 100%; 
    float: right; 
} 

.buyPanel { 
    width: 100%; 
    height: 230px; 
    margin: 40px 0 0 0; 
} 

.sellPanel { 
    width: 100%; 
    height: 230px; 
    margin: 40px 0 0 0; 
} 
+0

只是想知道是什么原因不只是让你的百分比较小,并根据您的容器大小手动制定出像素计算?我之所以问这个问题,只是因为calc()不被许多浏览器所支持,所以根据你的目标受众是什么,它可能在某些浏览器上不起作用。只是好奇:) – grimesd

+1

@grimesd - 现在所有浏览器都支持calc。只有IE的旧版本仍在使用中缺乏支持。 –

+1

@ori drori谢谢你的澄清 – grimesd

回答

4

使用calc()一个固定的量,以减少width

的计算值()函数CSS可以在任何地方使用的<length><frequency><angle><time><number>,或需要<integer>。使用calc(),您可以执行计算来确定CSS属性值。

可以减少其中之一的宽度:

.homeContentContainer { 
    position: absolute; 
    width: calc(60% - 40px); 
    margin: 0 auto; 
    top: 70px; 
    left: 0px; 
    right: 0px; 
} 

或分割的2个元素之间的区别:

.homeContentContainer { 
    position: absolute; 
    width: calc(60% - 20px); 
    margin: 0 auto; 
    top: 70px; 
    left: 0px; 
    right: 0px; 
} 

.leftCol { 
    width: calc(40% - 20px); 
    height: 100%; 
    float: left; 
} 
1

你也可以做到这一点与一个CSS grid。看看这个例子:

.container { 
 
    display: grid; 
 
    background-color: #eee; 
 
    height: 200px; 
 
    /* This makes .left width 40% and .right 60%*/ 
 
    grid-template-columns: 40% 60%; 
 
    grid-gap: 40px; /* 40px gap between .left and .right */ 
 
    width: 60%; 
 
    margin: 0 auto; 
 
    text-align: center; 
 
} 
 

 
.left { 
 
    background-color: yellow; 
 
} 
 

 
.right { 
 
    background-color: orange; 
 
}
<div class="container"> 
 
    <div class="left">Left</div> 
 
    <div class="right">Right</div> 
 
</div>

+1

grid-gap可以用来代替边距;) –

+0

@GCyrillus真的,我只是忘了它的名字lol谢谢! – Ikbel

相关问题