Css text line margin

text-indent

The text-indent CSS property sets the length of empty space (indentation) that is put before lines of text in a block.

Try it

Horizontal spacing is with respect to the left (or right, for right-to-left layout) edge of the containing block-level element’s content box.

Syntax

/* values */ text-indent: 3mm; text-indent: 40px; /* value relative to the containing block width */ text-indent: 15%; /* Keyword values */ text-indent: 5em each-line; text-indent: 5em hanging; text-indent: 5em hanging each-line; /* Global values */ text-indent: inherit; text-indent: initial; text-indent: revert; text-indent: revert-layer; text-indent: unset; 

Values

Indentation affects the first line of the block container as well as each line after a forced line break, but does not affect lines after a soft wrap break.

Inverts which lines are indented. All lines except the first line will be indented.

Formal definition

Initial value 0
Applies to block containers
Inherited yes
Percentages refer to the width of the containing block
Computed value the percentage as specified or the absolute length, plus any keywords as specified
Animation type a length, percentage or calc();
Читайте также:  :nth-child()

Formal syntax

Examples

Simple indent

HTML

p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. p> p> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. p> 

CSS

p  text-indent: 5em; background: powderblue; > 

Result

Skipping indentation on the first paragraph

A common typographic practice when paragraph indentation is present is to skip the indentation for the first paragraph. As the The Chicago Manual of Style puts it, «the first line of text following a subhead may begin flush left or be indented by the usual paragraph indention.»

Treating first paragraphs differently from subsequent paragraphs can be done using the adjacent sibling combinator, as in the following example:

HTML

h2>Lorem ipsumh2> p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eu venenatis quam. Vivamus euismod eleifend metus vitae pharetra. In vel tempor metus. Donec dapibus feugiat euismod. Vivamus interdum tellus dolor. Vivamus blandit eros et imperdiet auctor. Mauris sapien nunc, condimentum a efficitur non, elementum ac sapien. Cras consequat turpis non augue ullamcorper, sit amet porttitor dui interdum. p> p> Sed laoreet luctus erat at rutrum. Proin velit metus, luctus in sapien in, tincidunt mattis ex. Praesent venenatis orci at sagittis eleifend. Nulla facilisi. In feugiat vehicula magna iaculis vehicula. Nulla suscipit tempor odio a semper. Donec vitae dapibus ipsum. Donec libero purus, convallis eu efficitur id, pulvinar elementum diam. Maecenas mollis blandit placerat. Ut gravida pellentesque nunc, in eleifend ante convallis sit amet. p> h2>Donec ullamcorper elit nislh2> p> Donec ullamcorper elit nisl, sagittis bibendum massa gravida in. Fusce tempor in ante gravida iaculis. Integer posuere tempor metus. Vestibulum lacinia, nunc et dictum viverra, urna massa aliquam tellus, id mollis sem velit vestibulum nulla. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec vulputate leo ut iaculis ultrices. Cras egestas rhoncus lorem. Nunc blandit tempus lectus, rutrum hendrerit orci eleifend id. Ut at quam velit. p> p> Aenean rutrum tempor ligula, at luctus ligula auctor vestibulum. Sed sollicitudin velit in leo fringilla sollicitudin. Proin eu gravida arcu. Nam iaculis malesuada massa, eget aliquet turpis sagittis sed. Sed mollis tellus ac dui ullamcorper, nec lobortis diam pellentesque. Quisque dapibus accumsan libero, sed euismod ipsum ullamcorper sed. p> 

CSS

p  text-align: justify; margin: 1em 0 0 0; > p + p  text-indent: 2em; margin: 0; > 

Источник

Как задать расстояние между строк CSS?

Расстояние между строк CSS

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

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

Изменить расстояние между строк CSS мы можем при помощи трех свойств: line-height, margin и padding. Давайте рассмотрим подробнее каждый из этих способов.

Как задать расстояние между строк CSS с помощью line-height?

Итак, наиболее удобным свойством для задания расстояние между строк в CSS является свойство line-height, которое задает межстрочный интервал (как Microsoft Word) относительно размера шрифта.

Значение свойства line-height можно задавать при помощи:

  • множителя
  • в пикселях (px)
  • пунктах (pt)
  • относительных единицах (em)
  • процентах(%)
  • дюймах (in) и др

Кроме этого, значение line-height может наследоваться от родительского блока (inherit) и вычисляться автоматически (normal).

На мой взгляд, наиболее удобной единицей является множитель.

Вот наглядный пример использования изменения расстояние между строк CSS с помощью line-height:

Как задать межстрочный интервал CSS

При уменьшении ширины экрана слова подписи одной из иконок перестроились друг под друга. И так как line-height не был задан, слова просто склеились друг с другом.

Допишем для этого заголовка свойство line-height равное 1:

Вот что в результате получается:

Как увеличить высоту строки в CSS

Как видите, расстояние между словами увеличилось за счет появления отступов сверху и снизу слов.

Как задать расстояние между строк CSS с помощью margin и padding?

Так же, кроме line-height для регулирования отступа вы можете использовать свойства margin и padding, изменяя в свою очередь внешний и внутренний интервал абзаца или заголовка.

Текст без интервалов

Для данного фрагмента текста зададим нижний margin равный 15px:

Межстрочные интервалы в тексте

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

Точно такой же результат мы получили бы, если бы использовали свойство padding-bottom.

В результате, после рассмотрения приведенных примеров можно сделать вывод, что в случае, если вам важна аккуратность и симметрия текста, то наиболее подходящим инструментом для задания расстояния между строк CSS является свойство line-height.

Так же вы можете использовать задания расстояния между строк при помощи CSS-свойств margin-bottom и padding-bottom, но этот способ больше подходит для задания расстояний между абзацев, ссылок или пунктов списков.

Надеюсь, моя статья поможет вам разобраться с вариантами расстановки интервалов между строками в тексте и будет для вас полезна в вашей дальнейшей работе по созданию сайтов.

Если вам понравилась моя статья, пожалуйста, не забудьте поделиться ею в соцсетях и оставить комментарий, и если вам интересно читать мои статьи, обязательно подпишитесь на мою рассылку.

А на сегодня у меня все. До встречи в следующих статьях!

С уважением Юлия Гусарь

Источник

CSS Text Spacing

In this chapter you will learn about the following properties:

  • text-indent
  • letter-spacing
  • line-height
  • word-spacing
  • white-space

Text Indentation

The text-indent property is used to specify the indentation of the first line of a text:

Example

Letter Spacing

The letter-spacing property is used to specify the space between the characters in a text.

The following example demonstrates how to increase or decrease the space between characters:

Example

Line Height

The line-height property is used to specify the space between lines:

Example

Word Spacing

The word-spacing property is used to specify the space between the words in a text.

The following example demonstrates how to increase or decrease the space between words:

Example

White Space

The white-space property specifies how white-space inside an element is handled.

This example demonstrates how to disable text wrapping inside an element:

Example

The CSS Text Spacing Properties

Property Description
letter-spacing Specifies the space between characters in a text
line-height Specifies the line height
text-indent Specifies the indentation of the first line in a text-block
white-space Specifies how to handle white-space inside an element
word-spacing Specifies the space between words in a text

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

word-spacing

The word-spacing CSS property sets the length of space between words and between tags.

Try it

Syntax

/* Keyword value */ word-spacing: normal; /* values */ word-spacing: 3px; word-spacing: 0.3em; /* Global values */ word-spacing: inherit; word-spacing: initial; word-spacing: revert; word-spacing: revert-layer; word-spacing: unset; 

Values

The normal inter-word spacing, as defined by the current font and/or the browser.

Specifies extra spacing in addition to the intrinsic inter-word spacing defined by the font.

Examples

HTML

div id="mozdiv1">Lorem ipsum dolor sit amet.div> div id="mozdiv2">Lorem ipsum dolor sit amet.div> 

CSS

#mozdiv1  word-spacing: 15px; > #mozdiv2  word-spacing: 5em; > 

Accessibility concerns

A large positive or negative word-spacing value will make the sentences the styling is applied to unreadable. For text styled with a very large positive value, the words will be so far apart that it will no longer appear to be a sentence. For text styled with a large negative value, the words will overlap each other to the point where the beginning and end of each word is unrecognizable.

Legible word-spacing must be determined on a case-by-case basis, as different font families have different character widths. There is no one value that can ensure all font families automatically maintain their legibility.

Formal definition

Initial value normal
Applies to all elements. It also applies to ::first-letter and ::first-line .
Inherited yes
Percentages refer to the width of the affected glyph
Computed value absolute
Animation type a length

Formal syntax

Specifications

Источник

Оцените статью