CSS: выравнивание в определенной позиции - PullRequest
1 голос
/ 28 июля 2011

Я знаю, чего хочу, но я не знаю, как лучше всего это выразить, поэтому, пожалуйста, простите.

У меня есть пронумерованные заголовки на моей странице и абзацы после заголовков.Я хочу выровнять текст абзацев так же, как начало заголовка заголовка и номера заголовков, выравниваемых по правому краю, например, на 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?Было бы тривиально использовать таблицы, но я хотел бы поступить иначе, если есть более чистый способ.

Ответы [ 4 ]

6 голосов
/ 28 июля 2011

Вот как бы я это сделал:

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/

Обратите внимание, что:

  1. Для элементов HTML не заданы классы CSS - в этом нет необходимости (Результат: более чистый код)

  2. Нумерация генерируется автоматически с помощью счетчиков CSS, что означает, что вам не нужно обновлять нумерацию, когда вы хотите вставить элемент между другими элементами.

1 голос
/ 28 июля 2011

Проверьте 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;
}
1 голос
/ 28 июля 2011

Вы можете сделать что-то вроде этого, отрегулировав ширину и поле по мере необходимости (и в зависимости от глубины / длины номеров заголовков)

<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;}

http://jsfiddle.net/jasongennaro/VKP9Y/

1 голос
/ 28 июля 2011

Я полагаю, вы используете собственные номера? Вы сами размещаете их там без использования? Я думаю, что с этой системой.

В любом случае, я бы, вероятно, настроил некоторые div-ы, чтобы они выглядели так:

Краткое примечание : Вам нужно добавить clear: оба к основному контейнеру, чтобы они хорошо складывались.

<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>

Что-то вроде этого будет работать нормально, и вы можете использовать свои собственные стили для управления структурой / дизайном, но опять же, я не знаю, является ли это абсолютно лучшим способом.

...