CSS: Выравнивание текста
По умолчанию текст на веб-страницах выровнен по левому краю элемента, в котором он располагается, однако используя свойство text-align, можно переопределить, как будут выравниваться строки текста относительно границ элемента. Рассмотрим каждое из возможных значений:
- left — выравнивает текст по левому краю.
- right — выравнивает текст по правому краю.
- center — выравнивает текст по центру.
- justify — выравнивает текст по ширине, в таком тексте оба конца строки размещаются вплотную к внутренним краям элемента. Пробелы между словами в этом случае корректируются браузером так, что бы длина всех строк была строго одинаковая.
Примечание: свойство text-align работает только с блочными элементами, такими как абзац или div, выравнивая внутри них все строчное содержимое, включая изображения. Применение свойства к строчным элементам, таким как ссылка или span, не даст никакого эффекта.
Растянуть текст по ширине div
У меня есть div с фиксированной шириной, но текст внутри div может измениться.
Есть ли способ установить с помощью css или другого интервала между буквами, чтобы текст всегда заполнял div идеально?
7 ответов
Как сказал Марк, text-align:justify; является самым простым решением. Однако для короткого текста это не будет иметь никакого эффекта. Следующий код jQuery растягивает текст до ширины контейнера.
Он вычисляет пространство для каждого символа и устанавливает letter-spacing соответственно, чтобы текст растягивался до ширины контейнера.
Если текст слишком длинный для размещения в контейнере, он позволяет ему расширяться до следующих строк и устанавливает text-align:justify; в текст.
Текст на всю ширину страницы CSS
Чтобы выровнять текст на всю ширину страницы можно использовать свойство text-align со значением justify. Так текст будет выглядеть гораздо более аккуратно. Для этого можно задать класс для текста и вставлять его там, где необходимо.
Пример
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eleifend cursus leo, at fringilla dui mollis non. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus tortor massa, consectetur quis commodo quis, ullamcorper sed augue. Mauris eu efficitur turpis.
Stretch text to fit width of div
I have a div with a fixed width, but the text inside the div can change.
Is there a way of setting, with css or other, the spacing between the letters so the text always fills the div perfectly?
13 Answers 13
This can be done with text-align:justify and a small hack. See here:
The trick is to add an element after the text that pretends to be really long word. The fake word is actually a span element with display:inline-block and width:100% .
In my example the fake word is in red and given a height of 1em, but the hack will work even without it.
As Mark said, text-align:justify; is the simplest solution. However, for short text, it won’t have any effect. The following jQuery code stretches the text to the width of the container.
It calculates the space for each character and sets letter-spacing accordingly so the text streches to the width of the container.
If the text is too long to fit in the container, it lets it expand to the next lines and sets text-align:justify; to the text.
Here is a demo :
Even easier HTML/CSS method would be to use flexbox. It’s also immediately responsive. But worth noting SEO won’t pick it up if you were to use it as a h1 or something.
![]()
Maybe this could help:
![]()
I found a better solution for text shorter than one line, without any extra js or tag, only one class.
![]()
A little late to the party, but for a simple, pure CSS implementation consider using flexbox :
Not sure if wrapping each letter in a span (note any element will work) will mess with SEO, but I imagine search engines will strip tags from the innerHTML of tags used for important markup such as headings, etc. (Someone who knows SEO to confirm?)
![]()
MARCH 2018 If you are landing on this question in a more current time.
I was attempting do do what the OP asked about but with a single word and found success with the following:
1. Use a <span> and set css: span < letter-spacing: 0px; display:block>(this makes the element only as wide as the content)
2. On load capture the width of the span let width = $(‘span’).width();
3. Capture the length of the span let length = $(‘span’).length;
4. Reset the width of the span to the container $(‘span’).css(<'width','100%'>);
5. Capture the NEW width of the span (or just use the container width) let con = $(‘span’).width();
6. Calculate and set the letter spacing to fill the container $(‘span’).css(<'letter-spacing':(cont-width)/length>)
Obviously this can be converted to use vanilla js and it is useful even with most font styles including non mono-space fonts.