Letter spacing last letter css

CSS letter-spacing Property

The CSS letter-spacing property allows specifying the spaces between letters/characters in a text.

Values supported by letter-spacing include parent-relative values (percentage), font-relative values (em, rem), absolute values (px) and the normal property, which resets to the font’s default.

The letter-spacing property supports negative values.

The letter-spacing is transitionable that’s why the spacing will change smoothly if a transition is defined.

Initial Value normal
Applies to All elements. It also applies to ::first-letter and ::first-line.
Inherited Yes.
Animatable Yes.
Version CSS1
DOM Syntax object.style.letterSpacing = «5px»;

Syntax

letter-spacing: normal | length | initial | inherit;

Example of the letter-spacing property:

html> html> head> title>Title of the document title> style> p < letter-spacing: normal; > .spacing < letter-spacing: 4px; > .spacing-negative < letter-spacing: -4px; > style> head> body> h2>Letter-spacing property example h2> p>This is a paragraph. p> p class="spacing">This is a paragraph. p> p class="spacing-negative">This is a paragraph. p> body> html>

Result

SS letter-spacing Property

In the given example the first one is a normal paragraph, for the second paragraph the letter-spacing is set to 4px, and for the third paragraph a negative value is set (-4px).

Читайте также:  Jquery изменить html код элемента

In the example below the letter-spacing is used with the transition property. You need to hover over the text to see the transition.

Example of the letter-spacing property with the transition property:

html> html> head> title>Title of the document title> style> body < background-color: #fff; color: #666; font-size: 1em; font-family: Roboto, Helvetica Sans-serif; > .example1 < background-color: #666; color: #eee; padding: 1em; letter-spacing: .5em; -webkit-transition: letter-spacing .5s ease; transition: letter-spacing .5s ease; > .example1:hover < letter-spacing: normal; > .example2 < background-color: #eee; color: #666; padding: 1em; > style> head> body> h2>Letter-spacing property example h2> div class="example1"> p> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Necessitatibus earum ut alias doloremque esse. Porro maxime dicta veniam molestias sed modi sunt sapiente eum nostrum consequatur accusantium facilis blanditiis nihil. p> div class="example2"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ullam, facilis, sed, consectetur incidunt quia sint accusamus obcaecati quisquam asperiores officiis mollitia explicabo est ratione. Qui id ipsa ratione inventore nam! div> div> body> html>

Additional information

  • In almost all the browsers, if you define a value computing to less than 1px (subpixel values), the letter-spacing property will not be applied.
  • Letter-spacing lowercase letters is not a good idea.
  • You can animate this property using the CSS transitions.

Values

Value Description Play it
normal Means that there won’t be extra spaces between characters. It is the default value of this property. Play it »
length Defines an extra space between characters. Negative values are allowed. Play it »
initial Makes the property use its default value. Play it »
inherit Inherits the property from its parents element.
Читайте также:  Остановить все потоки java

Browser support

Источник

Remove letter-spacing from last letter

One of the frustrating things about the letter-spacing property is the addition of the letter-spacing you apply to the last letter of the text. This is fine when you have left aligned text, however if you right align or centre the text, you’re left with a little bit of space.

The problem

The solution

The solution is just one line of CSS. A margin-right equal to the letter-spacing you apply.

Additional tip

Set up a reusable class for any text that you want to apply letter-spacing to in em’s this means you don’t have to recalculate the additional spacing offset and can apply letter-spacing to any size text with it being proportional to that size.

Removing the excess underline from letter spacing

To remove the extra underline from text with letter spacing, the solution is not too elegant, nor is the extra underline. So it balances itself out. There are two solutions to this problem, however they’re not perfect. Both involve pseudo elements and a mix of positioning.

Method one: cover with a small box

The first one involves using a pseudo element and positioning a small box so it covers up the excess. The element has background colour that matches the one behind the element.

To understand how this works, I have a small square that is 1px wider than the letter-spacing. It’s positioned 1px outside of the element. I found that there was a half pixel or so that was still visible when you precisely match the excess.

Method two: create your own underline

To understand how this works, the right value must be equal to the letter-spacing amount. In this case it’s 3px. The colour of the underline is controlled by the background . This could also be a border.

Things to be aware of

  • They do not account for multiline
  • They must be inline-block to work effectively
  • It doesn’t work well with block elements

I’m a tea drinker, but it’s equally appreciated if you found the article useful.

Источник

Как я могу удалить межбуквенный интервал для последней буквы элемента в CSS?

Вот изображение моей HTML-страницы. Текстовое меню находится внутри блока div с выравниванием по правому краю и имеет межбуквенный интервал 1.2 м. Есть ли для этого псевдоселектор? Я не хотел бы прибегать к относительному позиционированию.

Мне бы хотелось, чтобы текстовое меню заканчивалось там, где заканчивается блок.

Div с выравниванием по правому краю, где межбуквенный интервал применяется ко всем символам строки

Я уже отметил лучший ответ, но меня попросили разметку независимо от CodeBlock. Вот.

Нужно увидеть вашу разметку. — BoltClock♦

Я обновил свой вопрос разметкой. — desbest

7 ответы

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

Чтобы ответить на ваш вопрос относительно псевдоселектора, насколько мне известно, псевдоселектора для каждого символа не существует. (РЕДАКТИРОВАТЬ: Поцарапайте это, там :First-Letter селектор, на который указал Джонас Дж. Дрейндж).

РЕДАКТИРОВАТЬ: здесь вы можете найти базовый образец: http://jsfiddle.net/teUxQ/

Наблюдения и советы этой статьи мы подготовили на основании опыта команды :first-letter псевдоэлемент тоже не точно «на символ» (в противном случае он был бы вызван :first-character ). Увидеть stackoverflow.com/questions/5649296/… — BoltClock ♦

закончил на этом, желая иметь текстовое оформление: подчеркивание… в этом случае это не работает. Есть подсказка? — Бен

Это неплохое решение, но если вы хотите text-align: center другой вариант, основанный на этой идее, — вместо этого установить margin-left в .5 * letter-spacing ( .6em в приведенном выше примере) и margin-right в -,5 * letter-spacing ( -.6em для приведенного выше примера — обратите внимание на right-margin — это отрицательный значение). — Кодер руки-ножницы

извините, опечатка в конце моего комментария выше: он должен читать «обратите внимание на margin-right — это отрицательный значение «(я пропустил пятиминутное окно редактирования по секундам). — Кодер руки-ножницы

Это работает для случая, но когда у вас есть text-decoration: underline; пространство все еще там. — Карлос Оливейра

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

Я использовал Opera 11.50. Последняя версия. Мне нравится нарезать чистый CSS-дизайн в Opera, так как Firefox отображает слишком хорошо, а IE9 может иметь причуды. — Desbest

да. Вот почему вы должны отправить отчет об ошибке. Если бы это была старая версия, я бы посоветовал вам сначала обновить ее. — лак

Я не думаю, что отправка отчета об ошибке будет хорошей идеей, поскольку IE / FF / WK / OP должны все реализовать эту причуду. Также я думаю, что если ошибка будет исправлена, это отрицательно повлияет на дизайн других веб-сайтов. — Desbest

Возможно, вы думаете о том, как это повлияет на ваш собственный веб-сайт, если вы реализуете обходной путь, а затем ошибка будет исправлена. Но будьте осторожны: рассуждения такого рода заставили нас на долгие годы застрять в IE6. — лак

Кажется, ошибка уже какое-то время (но ее можно исправить с помощью полной реализации css3): bugzilla.mozilla.org/show_bug.cgi?id=125390 — Родерик

Очевидно, это очень старый вопрос, но CSS, задействованный для вашего конкретного примера, тогда работал.

Он включает в себя сброс направления на противоположное, предоставление контекста форматирования вашему встроенному элементу и установку отрицательного отступа текста, равного межбуквенному интервалу.

Источник

How to Remove Letter-Spacing for the Last Letter of an Element in CSS

How can I remove letter-spacing for the last letter of an element in CSS?

You can set your element to have a right margin of -1.2em, which would counteract the letter spacing.

.menu-header-selector display:block; 
letter-spacing:1.2em;
margin-right:-1.2em;
text-align:right;
>

To answer your question regarding pseudo-selector, there isn’t a per character pseudo-selector as far as I’m aware. (EDIT: Scratch that, there’s the :First-Letter selector, which Jonas G. Drange pointed out).

EDIT: You can find a basic sample here: http://jsfiddle.net/teUxQ/

How can I remove the letter-spacing on the last letter of an a tag in CSS?

You could wrap the entire text part of the link in a span and use the margin-right: -10px technique to get this done.

body  
background-color: #1E1E96;

>

a
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;

color: #FFF;

text-decoration: none;

font-size: 12px;

>

.btn-wrapper
text-align: center;

margin: 100px auto;

>

.btn-wrapper a
text-transform: uppercase;

text-align: center;

letter-spacing: 10px;

padding: 15px 40px;

border: solid 2px #FFF;

>

.btn-wrapper a span
margin-right: -10px;

>

How to remove letter-spacing for the last letter of an input field with CSS?

The width of #partitioned is too small, and is causing the input field to scroll horizontally to accommodate the last digit. Change the width to width: 220px; and this will fix it:

CSS — Negate additional space added to last letter by letter-spacing property

The issue does indeed stem from using letter-spacing. According to the standard, when you increase the letter spacing the layout engine considers that extra space after the letter to be part of the letter’s width. So that extra space you see on the right is, in a way, what you asked for.

What it seems you want is for the letter spacing to put the actual letter in the middle, and surround each letter on both sides with letter-spacing/2. But I’m not sure that’s a feature of CSS. In fact, the letter spacing algorithms are user agent-dependent, so this may even work in different ways on different browsers.

So you’re left with ways to hack around this problem, like adding a -1em right margin/padding, but probably without a «true» solution.

How to achieve the last letter without letter-spacing in a text input field?

What about adding a padding-left of 1em ?

Here is an example, with the maxlength removed and a width added, so you can see that it is centered properly:

Note: This looks to only be an issue with some browsers. IE, shockingly, seems to correctly leave off the extra spacing unless there is an adjacent character. You might have to do some browser-specific code.

How to remove the space between words CSS

Your problem is because you’re adding multiple spaces together, but without in an inline text element, only one space will render. This is due to white space collapse. This is causing the space to render at the first letter-spacing , which is big at the start, and smaller at the end. Adjust your spacing accordingly and it should work, e.g. start each section with a space, instead of adding one at the start and end.

Depending on the font rendering’s actual size, you may still end up with some sub-pixel irregularity, but unless you want to remove all the spacing and add some margin to the tags, this is probably a decent starting point.

.sub-lead text-align: justify; 
font-family: 'Poppins', sans-serif;
font-weight: 300;
>

strong letter-spacing: 3px;
>



THE 8 5 2 EXPERIENCE 9 0 YOU 0 8 5 ARE

Источник

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