如何使 div 的间距相等,不仅在彼此之间均匀分布,而且在容器的两侧也均匀分布。
我想在纯/常规CSS中重新创建flexbox的“合理”+“空间周围”和“环绕”功能。
如下所示(使用手柄缩小):
.flex-container {
display: flex;
justify-content: space-around;
background-color: DodgerBlue;
flex-wrap: wrap;
}
.flex-container>div {
background-color: #f1f1f1;
width: 100px;
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
}
.resize {
resize: both;
overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)
<body>
<div class="flex-container resize">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
<p>A container with the justify-content property set to <em>space-around</em> will display its items with the equal amount of space around them.</p>
</body>
Run Code Online (Sandbox Code Playgroud)
我最接近的尝试可以在这里找到:问题:容器两侧的间距不相等。(使用手柄收缩):
.my-nonflex-container {
width: 100%;
display: inline-block;
background-color: DodgerBlue;
text-align: justify;
}
.spacer {
display: inline-block;
margin: 0 auto;
background-color: black;
}
.my-nonflex-container>div {
background-color: #faffff;
width: 100px;
margin: 10px;
text-align: center;
line-height: 75px;
font-size: 30px;
}
.stretch {
width: 100%;
display: inline-block;
height: 20px;
background-color: #003060;
color: white;
text-align: center;
margin-bottom: 20px;
}
.resize {
resize: both;
overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)
<body>
<div class="my-nonflex-container resize">
<div class="spacer">
<div>1</div>
</div>
<div class="spacer">
<div>2</div>
</div>
<div class="spacer">
<div>3</div>
</div>
<div class="spacer">
<div>4</div>
</div>
<div class="spacer">
<div>5</div>
</div>
<span class="stretch">stretcher workaround</span>
</div>
</div>
<p>A container with the text-justify property and a span-stretch to also justify "wrapped" content.</p>
</body>
Run Code Online (Sandbox Code Playgroud)
可以使用非 Flex CSS 在某种程度上复制 Flex 属性,但我不确定您是否能够仅使用 CSS 获得您想要的一切。
justify-content: space-around
我使用以下 CSS管理了一个副本:
<div class="not-a-flexbox">
<div class="box">
<p> 1 </p>
</div>
<div class="box">
<p> 2 </p>
</div>
<div class="box">
<p> 3 </p>
</div>
<div class="box">
<p> 4 </p>
</div>
<div class="box">
<p> 5 </p>
</div>
</div>
.not-a-flexbox {
display: table;
width: 100%;
}
.box {
display: table-cell;
text-align: center;
}
.box > p {
display: inline-block;
min-width: 60px;
min-height: 60px;
margin: 10px;
}
Run Code Online (Sandbox Code Playgroud)
在这里查看它的实际效果: https: //jsfiddle.net/kz60gnjw/
不幸的是我没能把这个包起来。
虽然这并不完全符合你的要求,但我确实设法得到了一个非弹性盒复制品justify-content: space-between
来工作和包装。您可以在这里查看代码: https: //jsfiddle.net/g1kvcn7z/
我的回答主要基于这篇文章:https ://kyusuf.com/post/almost-complete-guide-to-flexbox-without-flexbox
我无法以您想要的方式组合 Flexbox 的不同部分,但您也许能够找到我错过的东西。以防万一它有帮助,这里还有一些无需 Flexbox 即可复制 Flexbox 样式的示例: https: //codepen.io/msankhala/pen/PNawBK
归根结底,我认为在正确包装时,您可能不得不求助于使用媒体查询来更改布局(这有点违背了要点)。你的另一个选择当然是javaScript,但我没有建议你这样做,因为你在标题中排除了它。
如果这是用作不支持 Flexbox 的后备,那么我找到了这篇文章:https://medium.com/css-mine/flexbox-how-to-deal-with-older-browsers-fbf6eb8c7a65