Right align some text within a list item

2019-06-21 17:54发布

I have a nested unordered list which has main content on the left, and I would like to add options which are floated right, such that they are aligned on the right regardless of the level of indentation.

<ul>
<li> Item 1 <span class='options'> link </span> </li>
<li> Item 2 <span class='options'> link </span>
  <ul>
    <li>Item 3 <span class='options'> link </span> </li>
  </ul>
</li>
</ul>

I have the following css:

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

li {
    padding-left: 15px;
    width: 400px;
}

.options {
    float: right;
    width: 50px;
}

When this is used however the options span is aligned to the right, but 1 line below the expected line.

How can I get the options span to line up with the list item?

TIA, Adam

3条回答
时光不老,我们不散
2楼-- · 2019-06-21 18:17

If modifying the HTML code is OK, you could enclose "Item 1" in a first span and:

  • float it to left (still floating .options to the right)
  • use display: inline-block on both span and text-align: right on .options, instead of floats (no compatible with Fx2 though, and only working in IE6/7 because span is an inline elements by default. Would not work with div)
查看更多
该账号已被封号
3楼-- · 2019-06-21 18:18

Using this CSS:

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

li {
    padding-left: 15px;
    width:400px;
}
.options {
    float: right;
    width: 50px;
}
li li { width:385px} 

This unfortunately requires your to define a width minus the padding. depending on your flexibility this will work. Tested in Chrome 3.0.

查看更多
爷的心禁止访问
4楼-- · 2019-06-21 18:28

Instead of floating, you may want to try absolute positioning.

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

li {
    padding-left: 15px;
    width: 400px;
    position: relative;
}

.options {
    width: 50px;
    position: absolute;
    right: 0px;
}
查看更多
登录 后发表回答