CSS在元素之间平均分隔空格,但使用最大空格

时间:2018-09-06 15:22:01

标签: html css spacing

我正在使用不同的ul创建导航li,该导航应平均共享空白。

问题在于元素之间的空白应具有30px的最大宽度。右侧的链接应始终保持正确。

.container {
  display: flex;
  border: 1px solid red;
}
ul {
  margin: 0 30px 0px 0px;
  display: flex;
  list-style: none;
  padding: 0;
  flex-grow: 1;
  justify-content: space-between;
}
li {
  margin: 0;
  padding: 0px 5px;
  border: 1px solid green;
  flex-basis: 0;
}
li:first-child{
  padding-left: 0px;
}
.secondPart {
  margin-left:auto;
  flex-shrink: 0;
}
<div class=container>
  <ul>
    <li>my elem</li>
    <li>my elem 2</li>
    <li>my elem 3</li>
    <li>my elem 4</li>
  </ul>
  <div class=secondPart>
    <a>my link</a>
  </div>
</div>

问题总结:

li应该在元素之间具有动态空间,但是最大空间为30px。我添加了一个填充,因为它应该是min-space

不胜感激!

提琴: http://jsfiddle.net/kLu34f1a/14/

1 个答案:

答案 0 :(得分:0)

在li和jQuery上使用margin来测量子项的长度

这会让您接近。我建议为您的ul

添加最大宽度

该片段使用jQuery来衡量子项的长度。如果项目的总和大于容器宽度,则可以使用功能更改行项目的边距。您会注意到,如果添加更多li

,则会调用console.log函数

我将li的边距设置为15px(每边15像素,总共30个最大像素间隔)

var containerWidth = $("#li-container").outerWidth();

console.log(containerWidth);

var w = 0;
// the 'true' paramater inside the outerWidth function includes margins
$("#li-container li").each(function(){
  w += $(this).outerWidth(true);
});

console.log(w);

// if the total length of the line items is more than the container, do this event
if(w>containerWidth) {

$("#li-container li").each(function(){
$(this).css("margin", "0px 5px");
});

console.log(w);

}
.container {
  display: flex;
  border: 1px solid red;
}
ul {
  margin: 0 30px 0px 0px;
  display: flex;
  list-style: none;
  padding: 0;
  justify-content: center;
  max-width: 600px;
}
li {
  margin: 0 15px;
  padding: 0px 5px;
  border: 1px solid green;
  flex-basis: 0;
}
li:first-child{
  padding-left: 0px;
}
.secondPart {
  margin-left:auto;
  flex-shrink: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=container>
  <ul id="li-container">
    <li>my elem</li>
    <li>my elem 2</li>
    <li>my elem 3</li>
    <li>my elem 4</li>
  </ul>
  <div class=secondPart>
    <a>my link</a>
  </div>
</div>