gpt4 book ai didi

html - 将 div 与百分比宽度和以像素为单位的边距相结合

转载 作者:技术小花猫 更新时间:2023-10-29 11:56:39 25 4
gpt4 key购买 nike

我有一个包含多个元素的页面,这些元素的宽度为 33.33% 以填满页面的整个宽度。但是,我想在元素之间添加一个 20px 的边距(垂直和水平,但垂直是这里的问题),但只是在连续的第一个和第二个元素的右侧添加一个 20px 的边距,破坏了整个页面。 (从 fiddle 中删除注释掉的 CSS,看看我的意思)。

JSfiddle

现在,问题是:如何添加 20px 边距并确保所有 .item div 保持相同大小?我可以使用宽度的百分比并添加 .item 的删除宽度作为边距,但这永远不会是稳定的 20px,因为它是百分比。

HTML

<div id="main">
<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 class="item">9</div>
<div class="item">10</div>
<div class="item">11</div>
<div class="item">12</div>
</div>

CSS

#main .item {
height: 100px;
width:33.33%;
float:left;
text-align: center;
}
#main .item:nth-child(3n+1) {
background: red;
}
#main .item:nth-child(3n+3) {
background: yellow;
}
#main .item:nth-child(3n+2) {
background:lightblue;
}
/*.item:nth-child(3n+1), .item:nth-child(3n+2) {
margin-right: 20px !important;
}*/

最佳答案

你可以使用 calc()33.33% 中减去 20px

在这种情况下,您将使用 width: calc(33.33% - 20px) 来替换边距。

Updated Example

#main .item:nth-child(3n+1),
#main .item:nth-child(3n+2) {
width: calc(33.33% - 20px);
margin-right: 20px;
}

不幸的是,这将导致元素的宽度不同(因为 20px 并未从所有元素中减去)。更好的解决方案是从所有元素中减去 13.33px (40px/3px):

Updated Example

#main .item {
height: 100px;
width: calc(33.33% - 13.33px);
float:left;
text-align: center;
}

关于html - 将 div 与百分比宽度和以像素为单位的边距相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29210902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com