水平列表项,

时间:2019-02-12 19:19:39

标签: html css flexbox

我正在尝试在水平导航栏上<li>个元素之间放置一条细灰色线,以提供元素之间的连接感。代码如下。如何在这些元素之间添加一条简单的线?

ul {
    display: flex;
    align-items: stretch; /* Default */
    justify-content: space-between;
    width: 100%;
    margin: 0;
    padding: 0;
}
li {
    display: block;
    flex: 0 1 auto; /* Default */
    list-style-type: none;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

4 个答案:

答案 0 :(得分:3)

以下是每个li之间的一行示例。

enter image description here

  • position: relative添加到ul,使其成为:after元素的父元素
  • 使用垂直平移将字符:after定位在字符的垂直中间
  • z-index提供background-colorli,使它们保持在灰线的“顶部”

ul {
    display: flex;
    align-items: stretch; /* Default */
    justify-content: space-between;
    width: 100%;
    margin: 0;
    padding: 0;
    position: relative;
}

li {
    display: block;
    flex: 0 1 auto; /* Default */
    list-style-type: none;
    background-color: white;
    padding: 0 0.75em;
    z-index: 1;
}

li:first-child {
    padding-left: 0;
}

li:last-child {
    padding-right: 0;
}

ul:after {
    content: '';
    border-bottom: 1px solid lightgray;
    position: absolute;
    transform: translateY(-50%);
    top: 50%;
    width: 100%;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

答案 1 :(得分:1)

您还可以进行简单的背景着色:

ul {
  display: flex;
  justify-content: space-between;
  margin: 0;
  padding: 0;
  background:linear-gradient(#ccc,#ccc)  center/100% 1px no-repeat;
}

li {
  list-style-type: none;
  background-color: white;
  padding: 20px;
  font-size:25px;
}

li:first-child {
  padding-left: 0;
}

li:last-child {
  padding-right: 0;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

这是提高透明度的一种方法:

ul {
  display: flex;
  justify-content: space-between;
  margin: 0;
  padding: 0;
  background:
    linear-gradient(blue,blue) left  50px top 50%,
    linear-gradient(blue,blue) right 50px top 50%,
    linear-gradient(blue,blue) center;
  background-size:calc((100% - 4*50px)/3) 1px;
  background-repeat:no-repeat;
}

li {
  list-style-type: none;
  width: 50px;
  font-size:25px;
  text-align:center;
}

body {
 background:pink;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

答案 2 :(得分:-1)

如果您不介意在导航栏上居中放置文本,则此解决方案应该可以为您解决。

ul {
  display: flex;
  align-items: stretch; /* Default */
  justify-content: space-between;
  width: 100%;
  margin: 0;
  padding: 0;
}
li {
  display: block;
  flex: 0 1 auto; /* Default */
  list-style-type: none;
  flex:1;
  text-align:center;
  border-right:1px solid gray;
}
li:last-of-type{
  border-right:none;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

答案 3 :(得分:-1)

我不太了解“中间”一词,但是您可以添加:

li { border-left: 1px solid gray; border-right: 1px solid gray;

就像我说的那样,不确定这是否是您的意思。 :)