css - how to position <li> in horizontal <ul>?

社会主义新天地 提交于 2021-01-27 18:00:59

问题


I have section, which contains horizontal ul, which contains four li's, as following:

#header-strip ul {
    display: flex;
    justify-content: space-between;
    margin: 0;
    padding: 0;
    height: 4vh;
    width: 100%;
    background-color: grey;
    list-style-type: none;
}

#header-strip li {
  display: inline;
}
<section id="header-strip">
    <ul>
      <li>meant to be left</li
      ><li>meant to be centered</li
      ><li>meant to be just before last</li
      ><li>meant to be right</li
      >
    </ul>
  </section>

Requirements:
- first item at left with some small percentage offset of screen edge
- second item centered in the middle
- third item to be at right, with some percentage space between to fourth
- fourth item at right, with percentage offset from screen edge

I am able to position li's with basic justify-content: space-between;, but don't know how to position it the custom way.

It should look like this:


回答1:


Simply change the margin of the second element and make it auto

As a side note: with flexbox you don't need to worry about whitespace and no need to define element as inline

#header-strip ul {
  display: flex;
  margin: 0;
  padding: 0;
  color:#ffff;
  width: 100%;
  background-color: grey;
  list-style-type: none;
}

#header-strip li {
 margin:0 2%;
}

#header-strip li:nth-child(2) {
  margin: auto;
}
<section id="header-strip">
  <ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>

  </ul>
</section>



回答2:


if you are using flexbox:

<section id="header-strip">
    <ul>
      <li>meant to be left</li
      ><li class="fill">meant to be centered</li
      ><li>meant to be just before last</li
      ><li>meant to be right</li
      >
    </ul>
  </section>

//css

.fill {
    flex-grow: 2;
}


来源:https://stackoverflow.com/questions/50708939/css-how-to-position-li-in-horizontal-ul

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!