Explain Codes LogoExplain Codes Logo

Css :first-letter not working

html
css-selectors
pseudo-elements
typography
Anton ShumikhinbyAnton Shumikhin·Nov 1, 2024
TLDR
.element::first-letter { font-size: 200%; color: red; }

Block-level containers only for ::first-letter. Examine if the element is <p>, <div>, or suchlike. Immediate inline offspring, such as <span>, invalidate ::first-letter. For context, use :: designed for modern browsers; : is more about compatibility with older versions.

Identifying suitable elements

Remember, for ::first-letter to work, your targeted HTML element must be a block-level container. Typical block elements include <p>, <div>, <h1> to <h6>, <li>, etc.

/* Sherlock Holmes of HTML, elementary my dear Watson */ .block-element::first-letter { font-size: larger; }

Don't apply ::first-letter to inline elements like <span> or <a> expecting it to work. If you still prefer using an inline element, set its display property to block or inline-block.

/* Doc says, "I'm in block now, feeling dizzy" */ .inline-element { display: block; }

Paying attention to the first content

This pseudo-element will skip any non-letter content or tags that precede the first-letter. So, you might want to avoid preceding the ::first-letter with a space, punctuation, or tag.

/* "Hey, is it a bird? ...No, it's just a space!" */ .element::first-letter { background-color: yellow; }

Addressing :before pseudo-element

If you used :before to bring about some content and you want to ::first-letter to point to the actual text instead of the introduced content, navigate carefully.

/* Wink wink, I came before everything eh! */ .element:before { content: "★"; } .element::first-letter { font-size: 200%; color: orange; }

In this case, since before is applied, your ::first-letter is actually the first star (★), not the first letter of your .element text.

Understanding pseudo-class concept

The ::first-letter selector is a pseudo-element which can be seen as a specific type of pseudo-class. They style specific parts of elements, thus adding more precision to your CSS.

/* "I know Kung-Fu. And by Kung-Fu, I mean styling" */ .kung-fu-class::first-letter { text-transform: uppercase; }

Balancing style and compatibility

A critical aspect is the element and its compatibility. The wrong combination can mean ::first-letter won't have any effect. Make sure to use :: for modern browsers and : for broader, older browser compatibility.

When using ::first-letter, also keep typography in mind. Too much styling might interfere with your overall design.

Whether you're an experienced coder looking for an argument on the behavior of ::first-letter or a beginner who wants more examples and in-depth exploration, I strongly recommend the MDN documentation.