CSS:在某个位置对齐

glm*_*ndr 1 css text-alignment

我知道我想要什么,但我不知道如何最好地表达它,所以请原谅.

我的页面中有头条新闻,标题后面的段落.我希望将段落的文本与标题标题的开头相对应,并将标题的编号与右侧对齐,例如标题标题的0.5em.

以下是等宽字体的示例:

    1. Introduction
       This is the beginning of the introduction.

  1.1. Sub header
       Another paragraph here and when it comes to having 
       another line, it is indented as the first one.

1.1.1. Sub-sub header
       Notice how the headlines and paragraphs are exactly
       aligned, whereas the numbers in the headlines are shifted
       to the right ?

  1.2. Sub header 2
       I'm sure you get the picture...
Run Code Online (Sandbox Code Playgroud)

在HTML/CSS中实现这一目标的最佳方法是什么?使用表格会很简单,但如果有更清洁的方法,我希望不这样做.

Šim*_*das 6

我就是这样做的:

HTML:

<ul id="list">
    <li>
        <h2>Intro<em></em></h2>
        <p>This is the beginning of the introduction.</p>
    </li>
    <li>
        <h3>Sub header<em></em></h3>
        <p>Another paragraph here and when it comes to having 
            another line, it is indented as the first one.</p>
    </li>
    <li>
        <h4>Sub-sub header<em></em></h4>
        <p>Notice how the headlines and paragraphs are exactly
            aligned, whereas the numbers in the headlines are shifted
            to the right ?</p>
    </li>
    <li>
        <h3>Sub header 2<em></em></h3>
        <p>I'm sure you get the picture...</p>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

CSS:

#list {
    counter-reset: level1 0 level2 0 level3 0;
    margin-left:50px;
}

#list h2,
#list h3,
#list h4 { margin-left:-50px; }

#list em { float:left; width:40px; padding-right:10px; text-align:right; }

#list h2 em:before {
    counter-increment: level1 1;
    content: counter(level1, decimal) ".";
}

#list h3 em:before {
    counter-increment: level2 1;
    content: counter(level1, decimal) "." counter(level2, decimal) ".";    
}

#list h4 em:before {
    counter-increment: level3 1;
    content: counter(level1, decimal) "." counter(level2, decimal) "." counter(level3, decimal) ".";    
}
Run Code Online (Sandbox Code Playgroud)

现场演示: http ://jsfiddle.net/9bkwQ/

请注意:

  1. HTML元素上没有设置CSS类 - 没有必要(结果:更干净的代码)

  2. 编号是通过CSS计数器自动生成的,这意味着只要您想在其他项目之间插入项目,就不必更新编号.