HTML-CSS: Custom text selection
HTML-CSS : Exercise-2 with Solution
Using HTML, CSS change the styling of text selection.
- Use the ::selection pseudo-selector to style text within it when selected.
HTML Code:
<!--License: https://bit.ly/3GjrtVF--><!-- License information -->
<!DOCTYPE html><!-- Document type declaration -->
<html><!-- Opening HTML tag -->
<head><!-- Head section containing metadata -->
<meta charset="utf-8"><!-- Character encoding declaration -->
<meta name="viewport" content="width=device-width"><!-- Viewport meta tag for responsive design -->
<title>Using HTML, CSS change the styling of text selection</title><!-- Title of the HTML document -->
</head><!-- Closing head tag -->
<body><!-- Body section of the HTML document -->
<div class="w3rcontainer"><strong>Preview:</strong><!-- Container div for preview with heading -->
<p class="custom-text-selection">Select some of this text.</p><!-- Paragraph element with custom class for text selection -->
</div><!-- Closing w3rcontainer div -->
</body><!-- Closing body tag -->
</html><!-- Closing HTML tag -->
Explanation:
- The HTML document contains a paragraph with a custom class for changing the styling of text selection.
- The paragraph prompts the user to select some text.
- Comments are provided to explain each section of the HTML code, including the purpose of each element and attribute.
- The license information is included as a comment at the beginning of the document.
CSS Code:
<style> /* Opening style tag for CSS */
::selection {
/* CSS rule for default text selection */
background: orange; /* Background color set to orange */
color: black; /* Text color set to black */
}
.custom-text-selection::selection {
/* CSS rule for custom text selection with class custom-text-selection */
background: green; /* Background color set to green */
color: white; /* Text color set to white */
}
</style><!-- Closing style tag -->
Explanation:
- Comments are provided in HTML and CSS to explain each section of the code.
- The HTML comment <!-- Opening style tag for CSS --> indicates the start of the CSS code block.
- Within the CSS code block, comments are used to describe each CSS rule and its purpose.
- The HTML comment <!-- Closing style tag --> marks the end of the CSS code block.
HTML-CSS Editor:
See the Pen html-css-practical-exercises by w3resource (@w3resource) on CodePen.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/html-css-exercise/html-css-practical-exercises/html-css-practical-exercise-2.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics