我知道我想要什么,但我不知道如何最好地表达它,所以请原谅。
我的页面中有头条新闻,标题后面的段落。我希望将段落的文本与标题标题的开头相对应,并将标题的编号与右侧对齐,例如标题标题的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...
在HTML / CSS中实现此目的的最佳方法是什么? 使用表格是微不足道的,但如果有更清洁的方法,我希望不这样做。
答案 0 :(得分: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>
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) ".";
}
现场演示: http://jsfiddle.net/9bkwQ/
请注意:
HTML元素上没有设置CSS类 - 没有必要(结果:更清洁的代码)
编号是通过CSS计数器自动生成的,这意味着只要您想在其他项目之间插入项目,就不必更新编号。
答案 1 :(得分:1)
我想你在使用自定义数字?你是不是自己把它们放在那里?我用这个系统想象一下。
无论哪种方式,我可能会设置一些看起来像这样的div:
快速注释:您需要在主容器中添加clear:both以使它们堆叠得很好。
<div style="display:inline-block; width:100%; clear:both")
<div style="float:left; margin-right:5px">
1.
</div>
<div style="float:left">
The first headline
</div>
</div>
这样的东西可以正常工作,你可以使用自己的风格来操纵结构/设计,但同样,我不知道它是否是绝对最好的方式。
答案 2 :(得分:1)
在这里查看一个JSFiddle:http://jsfiddle.net/uvQsR/2/
<div class="section">
<span class="number">1.1.</span>
<h4 class="heading">Sub header</h4>
<p> Another paragraph here and when it comes to having
another line, it is indented as the first one. </p>
</div>
用css
.section {
padding-left:40px;
}
.number{
text-align:right;
margin-left:-40px;
float:left;
width:40px;
}
答案 3 :(得分:1)
你可以做这样的事情,根据需要调整宽度和边距(并根据标题数字的深度/长度)
<h2 class="number">1.</h2><h2 class="text">Introduction</h2>
<p>This is the beginning of the introduction.</p>
<h2 class="number">1.1</h2><h2 class="text">Sub header</h2>
<p>Another paragraph here and when it comes to having<br />
another line, it is indented as the first one.</p>
CSS
h2.number{display:inline-block; width:30px;}
h2.text{display:inline-block;}
p{margin-left:30px; margin-bottom:10px;}