gpt4 book ai didi

html - 使用 flexbox 为 li 添加边距

转载 作者:太空宇宙 更新时间:2023-11-04 11:14:29 24 4
gpt4 key购买 nike

我正在使用 flexbox布置我的东西。我有 5 lis (到目前为止,但这会改变),宽度如下:flex-basis:calc(100%/3) .所以会有 3 li's在每一行中。包装器 ( ul ) 有一个 width70% .

到目前为止一切顺利。问题是,当我为 li's 添加边距时.当我添加 marginli's , 只会有 2 个 li's每行都有一些额外的空间,但我需要 3 个。

所以我找到了 2 个给我其他问题的解决方案:

  • 一种解决方案是将边距添加到 li's ,比方说 10px .然后减去20px (10 * 2) 来自 widthheight每个 li's .我不能那样做,因为我需要 li's是我设置的大小,而不是更小。

  • 另一个解决方案是设置 justify-contentspace-aroundspace-between .问题是我需要 lis在列和行中(如图表)。如果我改变 justify-content , li's不会像订单那样出现在图表中。

有没有办法给 li 添加边距?不影响任何其他属性(property)?

(如果这是唯一的选择,我愿意接受 JavaScript/JQuery。)

JSFiddle

这是一个代码片段:

body, html {
height:100%; margin: 0; padding:0;
}
#flexWrapper {
display: flex;
justify-content: center;
height: 100%;
align-items: center;
overflow: auto;
}
#flexContainer {
width: 70%;
background-color:yellow;
list-style-type: none;
padding: 0;
margin: auto;

display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: center;
align-content:flex-start;
}
li {
background-color: tomato; border: 1px solid black; height:50px;
box-sizing: border-box;
flex-basis:calc(100%/3);
margin:10px;
}
<div id="flexWrapper">
<ul id="flexContainer">
<li class="flex-item">1</li>
<li class="flex-item">2</li>
<li class="flex-item">3</li>
<li class="flex-item">4</li>
<li class="flex-item">5</li>
</ul>
</div>

最佳答案

好的,所以我终于得到了有效的答案!我必须部分归功于@Syahrul 提出这个想法(在评论中)。

基本上我要做的就是这个。如果我们想增加 1.5% 的边距,我们将添加 (1.5 * 2) * 3 ( 1.5 * 2 因为边距在每个 li 的两侧。 * 3 because we have 3 li 的 in every row.) to the 宽度 of the wrapper ('#flexContainer ), 所以我们有 79% #flexContainer 的宽度.

接下来,我们将减去 3% (边距大小 (1.5 * 2))来自 widthli .那就是 flex-basis:calc(100%/3 - 3%) .

就是这样!这是更新的 JSFiddle

body, html {
height:100%; margin: 0; padding:0;
}
#flexWrapper {
display: flex;
justify-content: center;
height: 100%;
align-items: center;
overflow: auto;
}
#flexContainer {
width: 79%;
background-color:yellow;
list-style-type: none;
padding: 0;
margin: auto;

display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: flex-start;
align-items: center;
align-content:flex-start;
}
li {
background-color: tomato; border: 1px solid black; height:100px;
box-sizing: border-box;
flex-basis:calc(100%/3 - 3%);
margin:1.5%;
}
<div id="flexWrapper">
<ul id="flexContainer">
<li class="flex-item">1</li>
<li class="flex-item">2</li>
<li class="flex-item">3</li>
<li class="flex-item">4</li>
<li class="flex-item">5</li>
</ul>
</div>

关于html - 使用 flexbox 为 li 添加边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335244/

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