HTML Pseudo Elements: A Comprehensive Guide

HTML Pseudo Elements: A Comprehensive Guide

Table of contents

No heading

No headings in the article.

HTML pseudo elements are used to style specific parts of an HTML element. They are defined using a special syntax, which starts with a colon (:). For example, you can use the :first-line pseudo element to style the first line of a paragraph element. You can also use the :before and :after pseudo elements to add content before or after an element, respectively. These pseudo elements are useful for adding specific styling to certain parts of a webpage without having to create additional HTML elements.

  • :first-line - Styles the first line of a text element. Example: p:first-line { font-weight: bold; }

  • :first-letter - Styles the first letter of a text element. Example: p:first-letter { font-size: 2em; }

  • :before - Inserts content before an element. Example: p:before { content: "Introduction: "; }

  • :after - Inserts content after an element. Example: p:after { content: " - End"; }

  • :hover - Styles an element when the user hovers over it. Example: a:hover { color: blue; }

  • :active - Styles an element when the user clicks on it. Example: button:active { background-color: gray; }

  • :focus - Styles an element when it has focus. Example: input:focus { border: 2px solid blue; }

  • :visited - Styles a link after it has been visited. Example: a:visited { color: purple; }

  • :link - Styles a link before it has been visited. Example: a:link { color: blue; }

  • :target - Styles an element when it is the target of a link. Example: h2:target { background-color: yellow; }

  • :enabled - Styles an enabled form element. Example: input:enabled { background-color: white; }

  • :disabled - Styles a disabled form element. Example: input:disabled { background-color: gray; }

  • :checked - Styles a selected radio button or checkbox. Example: input[type="checkbox"]:checked { background-color: green; }

  • :nth-child - Styles a specific child element of its parent. Example: tr:nth-child(even) { background-color: gray; }

  • :nth-of-type - Styles a specific type of child element of its parent. Example: p:nth-of-type(2) { font-style: italic; }

  • :last-child - Styles the last child element of its parent. Example: li:last-child { font-weight: bold; }

  • :first-of-type - Styles the first element of its type within its parent. Example: h3:first-of-type { text-transform: uppercase; }

  • :only-of-type - Styles an element if it is the only element of its type within its parent. Example: p:only-of-type { margin: 0; }

  • :only-child - Styles an element if it is the only child of its parent. Example: li:only-child { font-style: italic; }

  • :not - Styles all elements that do not match a specific selector. Example: p:not(.special) { color: gray; }

Note: These are just examples, you can style based on your requirement and availability of the property.