How do we style HTML elements using the span tag ?


We use <span> tag to color a part of text or a part of the document. This tag is mainly used to group similar content together for easy styling. We use inline style for <span> tag, as it applies a style to inline elements.

If we want to make some text or any other content different from the rest, we wrap it in a <span> tag, and add class attribute to identify, then add attribute value for styling.

Syntax

Following is the syntax for the <span> tag.

<span class=" ">Text…</span>

Example 1

Given below is an example to style HTML element using span tag.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p> <span style="color:green;font-weight:bolder"> Major Sandeep Unnikrishnan</span>was an officer in the Indian Army serving in the elite 51 Special Action Group of the National Security Guards. He was martyred in action during the November 2008 Mumbai attacks. <span style="background-color: yellow;"> He was consequently awarded the Ashoka Chakra, India's highest peacetime gallantry award, on 26 January 2009 by the president Pratibha Patil.</span> </p> </body> </html>

Following is the output for the above example program.

Example 2

Given below is an example to style HTML element using span tag.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <p> <span style="text-transform: uppercase; font-weight:bolder"> Major Sandeep Unnikrishnan</span> was an officer in the Indian Army serving in the elite 51 Special Action Group of the National Security Guards. He was martyred in action during the November 2008 Mumbai attacks. <span style="font-family:cursive; color: green"> He was consequently awarded the Ashoka Chakra, India's highest peacetime gallantry award, on 26 January 2009 by the president Pratibha Patil.</span> </p> </body> </html>

Following is the output for the above example program.

Example 3

You can try to run the following code to learn the usage of a <span> tag. Here, we will be using the <span> tag inside the <p> tag.

<!DOCTYPE html> <html> <head> <title>HTML span Tag</title> </head> <body> <p>Java is a Programming language widely followed. <span style = "color:#FF0000;">Developed by James Gosling. </span>This is demo text.</p> <p> <span style = "color:#8866ff;"> Current Version: 1.8 </span> </p> </body> </html>

Updated on: 19-Oct-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements