设置有序列表的样式,使数字显示为左对齐且位于项目上方?

时间:2010-10-18 08:12:54

标签: html css html-lists

我认为这很容易,但我没有找到一个好的解决方案(也许我也使用了错误的搜索条件)。

我想为有序列表设置样式,以便项目显示为:

  

1

     

第一项

     

2

     

第二项

     

3

     

第三项

有没有办法简单地用CSS做到这一点?

非常感谢提前!

5 个答案:

答案 0 :(得分:3)

您可以尝试以下方式:

<style>
    ol {
      list-style-position: inside;
      padding-left: 0;
    }
</style>

<ol>
    <li>&nbsp;<div>foobar</div></li>
    <li>&nbsp;<div>wah la</div></li>
</ol>

适用于FF和Chrome,但我目前的机器上没有IE可供尝试。

答案 1 :(得分:2)

AFAIK,CSS does not allow you to have a lot of control关于列表项相对于“子弹”(或数字或其他)的位置......所以最好直接生成数字HTML ,在服务器端,或在客户端通过Javascript ...

然而,以下工作(至少在Firefox中),但相当丑陋(中间有br: - /)

<html>
  <head>
   <style type="text/css">
    li > p{
        margin-left:-30px;
        margin-top:-10px;
    }
   </style>
  </head>
  <body>
    <ol>
        <li><br/><p>item 1</p></li>
        <li><br/><p>item 2</p></li>
    </ol>
  </body>
</html>

我们的想法是使用br强制列表项的内容在另一行上,然后在内容上应用一些负边距< / strong>将它移动到你想要的位置......这当然不是一个很好的解决方案......此外,我认为每个浏览器都可以生成“list-index”,所以没有好办法让它适用于所有浏览器...

答案 2 :(得分:2)

您可以将content属性与:before伪元素和\a换行符一起使用:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>OL Test</title>
        <style type="text/css">
        li:before {
            content: "\a";
            white-space: pre;
        }
        </style>
    </head>
    <body>
        <ol>
            <li>Item one</li>
            <li>Item two</li>
            <li>Item three</li>
        </ol>
    </body>
</html>

这应该适用于支持CSS 2.1的浏览器。

答案 3 :(得分:0)

它绝对必须是有序列表吗?

如果你正在动态生成内容,那么你总是可以自己输出数字,然后按照你喜欢的方式格式化标记 - 而不是试图通过做一些“聪明”来强制浏览器,通过做某事来简化情况'智能“

答案 4 :(得分:0)

我知道这个问题真的很老了,但我在寻找相同的答案时最终找到了它,并且提供的这些答案并没有完全按照我的需要去做。我刚刚在CSS中使用“计数器”学习了这个非常酷的技术。

您的CSS看起来像这样:

ol {
   list-style: none; /* Remove default numbers */
   counter-reset: item;
}
ol li {
   counter-increment: item;
}
ol li:before {
   content: counter(item); /* Add the numbers as content in the before pseudo */
   /* Continue styling as needed, changing, fonts, position, etc. */
   display: block;
}

JS Fiddle