span Tag | HTML

Опубликовано: 1 Марта, 2022

Элемент HTML span - это общий встроенный контейнер для встроенных элементов и содержимого. Он используется для группировки элементов для целей стилизации (с использованием атрибутов class или id). Лучший способ использовать его, когда нет других доступных семантических элементов. span очень похож на тег div, но div является тегом уровня блока, а span - встроенным тегом . Тег Span - это парный тег, это означает, что у него есть как открытый (<), так и закрывающий (>) тег, и он является обязательным для закрытия тега.

  • Тег span используется для группировки inline-элементов.
  • Тег span сам по себе не вносит никаких визуальных изменений.
  • span очень похож на тег div, но div является тегом уровня блока, а span - встроенным тегом .

Тег написан так:
Синтаксис:

 <span class = ""> Немного текста ............. </span>

В приведенном ниже примере предположим, что мы хотим трижды написать GeeksforGeeks в трех строках с полужирным шрифтом, курсивом, подчеркиванием, зеленым цветом с font-family = courier new, поэтому нам нужно использовать много тегов HTML, таких как <b>, <i>, < u>, <font> каждый раз в каждой строке, и мы хотим внести изменения, необходимо изменить каждый тег.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>GeeksforGeeks span tag</title>
</head>
<body>
    <h2>Welcome To GFG</h2>
  
<!-- First Line  -->    
<font color="009900" size="6">
    <b>
       <u>
           <i>GeeksforGeeks</i>
       </u>
    </b>
</font>
  
    </br>
  
<!-- Second Line  -->    
<font color="009900" size="6">
    <b>
       <u>
           <i>GeeksforGeeks</i>
       </u>
    </b>
</font>
  
    </br>
  
<!-- Third Line  -->    
<font color="009900" size="6">
    <b>
       <u>
           <i>GeeksforGeeks</i>
       </u>
    </b>
</font>
      
  
</body>
</html>                    

Выход:

But by using <span> tag we can reduce code and HTML Attributes see below example will display the same output as above example with using <span> tag by applying CSS in a span tag.
Example:

<!DOCTYPE html>
<html>
   <head>
      <title>GeeksforGeeks span tag</title>
       
     <!-- style for span tag  -->    
     <style type=text/css>
         span{
         color: green;
         text-decoration: underline;
         font-style: italic;
         font-weight: bold;
         font-size: 26px;
         
      </style>
   </head>
   <body>
      <h2>Welcome To GFG</h2>
      <span>GeeksforGeeks</span></br>
      <span>GeeksforGeeks</span></br>
      <span>GeeksforGeeks</span></br>
   </body>
</html>

Выход:

As we know span is an inline tag it takes space as much as required and leaves space for other element let see it in below example all four-span element will display in the same line because each tag takes only necessary space and rest of space free for other elements.
Example:

<!DOCTYPE html>
<html>
   <head>
      <title>GeeksforGeeks span tag</title>
   </head>
   <body>
      <h2>Welcome To GFG</h2>
       <!-- span tags with inline style/css  -->    
      <span style="background-color:powderblue;">
       GFG</span>
      <span style="background-color: lightgray;">
      -Contribute-</span>
      <span style="background-color: yellow;">
      Article</span>
      <span style="background-color: lightgreen;">
      GCET</span>
   </body>
</html>

Output:



A span tag can be used to set color/background color a part of a text: In below example inside paragraph applying three times span tag with different style.
Example:

<!DOCTYPE html>
<html>
   <head>
      <title>GeeksforGeeks span tag</title>
   </head>
   <body>
      <h2>Welcome To GFG</h2>
  
      <!-- Inside paragraph applying span tag with different 
      style -->    
      <p><span style="background-color:lightgreen">
         GeeksforGeeks</span> is A Computer Science
         Portal where you can<span style="color:blue;">
         Publish</span> your own <span style=
         "background-color:lightblue;">articles</span>
         and share your knowledge with the world!!
      </p>
   </body>
</html>

Output:

Manipulate javascript with span tag: In below example we add a span tag inside paragraph with id=”demo” we can changes its text by applying javascript in this example GFG will be changed “GeeksforGeeks” after clicking on Button.
Example:

<!DOCTYPE html>
<html>
   <body>
      <h2>Welcome to GFG</h2>
      <p> <span id="demo" 
         style="background-color:lightgreen;">GFG</span>
      A computer Science portal for Geeks</p>
  
    <!-- creating button in java script  -->    
    <button  type="button" onclick=
         "document.getElementById("demo").innerHTML =
                "GeeksforGeeks!!!"">Change Text!</button>
   </body>
</html>

Выход:
Перед нажатием кнопки

После нажатия на кнопку

Разница между тегом Div и тегом span

Тег div и span являются двумя общими тегами при создании страниц с использованием HTML и выполняют с ними разные функции, в то время как тег div является элементом уровня блока, а тег span - встроенным элементом. Тег div создает разрыв строки и по умолчанию создает разделение между текстом, который идет после тега как начального и до тех пор, пока тег не заканчивается на </div>. Тег div создает отдельные блоки или контейнеры для всех элементов внутри этого тега, таких как текст, изображения, абзацы.

Характеристики Div Tag Span Tag
Типы элементов Уровень блока В линию
Пространство / Ширина Содержит всю доступную ширину Требуется только необходимая ширина
Примеры Заголовки, абзац, форма Атрибут, изображение
Использует Веб-верстка контейнер для текста
Атрибуты Не требуется, с обычным css, класс Не требуется, с обычным css, классом

The span tag does not create a line break similar to a div tag, but rather allows the user to separate things from other elements around them on a page within the same line. avoiding of the line break, results only that selected text to change, keeping all the other elements around them same.
Below example will display the difference between span and div tag while div tag contains whole width and span tag contain only required width and rest parts are free for another element.

<strong>Example:</strong>
<html>
   <head>
      <title>gfg</title>
      <style type=text/css>
         p{
         background-color:gray;
         margin: 10px;
         }
           
           
         div
         {
         color: white;
         background-color: 009900;
         margin: 2px;
         font-size: 25px;
         }
         span
         {
         color: black;
         background-color: gray;
         margin: 5px;
         font-size: 25px;
         }
      </style>
   </head>
   <body>
<!-- below some div tags -->      
  
      <div > div tag   </div>
      <div > div tag   </div>
      <div > div tag   </div>
      <div > div tag   </div>
        
<!-- below some span tags -->      
      <span>span-tag</span>
      <span>span-tag</span>
      <span>span-tag</span>
      <span>span-tag</span>
   </body>
</html>

Выход:

Поддерживаемый браузер: поддерживаемые браузеры перечислены ниже.

  • Гугл Хром
  • Internet Explorer
  • Fire Fox
  • Опера
  • Сафари