HTML | Div Tag

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

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

  • Тег Div - это тег уровня блока
  • Это общий тег контейнера
  • Он используется для группы различных тегов HTML, чтобы можно было создавать разделы и применять к ним стиль.

As we know Div tag is block-level tag in this example div tag contain entire width. It will be displayed div tag each time on a new line, not on the same line.
Example 1:

<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;
}
</style>
   
</head>
  
 <body>
   <div > div tag   </div>
   <div > div tag   </div>
   <div > div tag   </div>
   <div > div tag   </div>
   
   </body>
</html>

Выход:

Как мы знаем, тег div используется для группировки элементов HTML вместе и предназначен для применения к ним CSS и веб-макета. Давайте посмотрим ниже пример без использования тега div. нам нужно применить CSS для каждого тега (в примере с использованием тегов H1 H2 и двух абзацев p )

Example 2:

<html>
   <head>
      <title>gfg</title>
      <style type=text/css>
         p{
         color: white;
         background-color: 009900;
         width: 400px;
         }
         h1
         {
         color: white;
         background-color: 009900;
         width: 400px;
         }
         h2
         {
         color: white;
         background-color: 009900;
         width: 400px;
         }
      </style>
   </head>
   <body>
      <h1>GeeksforGeeks</h1>
      <p>How many times were you frustrated while looking out
       for a good collection of programming/algorithm/interview
       questions? What did you expect and what did you get?
       This portal has been created to provide well written,
       well thought and well-explained solutions for selected
       questions.
      </p>
      <h2>GeeksforGeeks</h2>
      <p>GCET is an entrance test for the extensive classroom 
      program by GeeksforGeeks to build and enhance Data 
      Structures and Algorithm concepts, mentored by Sandeep 
      Jain (Founder & CEO, GeeksforGeeks).He has 7 years of 
      teaching experience and 6 years of industry experience.
      </p>
   </body>
</html>

Выход:

Creating Web Layout using Div Tag
The div tag is a container tag inside div tag we can put more than one HTML element and can group together and can apply CSS for them.
div tag can be used for creating a layout of web pages in the below examples shows creating a web layout
we can also create web layout using tables tag but table tags are very complex to modify the layout
The div tag is very flexible in creating web layouts and easy to modify. in below example will show grouping of HTML element using div tag and create block-wise web layout.
Example:

<html>
   <head>
      <title>gfg</title>
      <style type=text/css>
         .leftdiv
         {
         float: left;
         }
         .middlediv
         {
         float: left;
         background-color:gray
         }
         .rightdiv
         {
         float: left;
         }
         div{
         padding : 1%;
         color: white;
         background-color: 009900;
         width: 30%;
         border: solid black;
         }
      </style>
   </head>
   <body>
      <div class="leftdiv">
         <h1>GeeksforGeeks</h1>
         <p>How many times were you frustrated while looking out
         for a good collection of programming/algorithm/interview
         questions? What did you expect and what did you get?
         This portal has been created to provide well written,
         well thought and well-explained solutions for selected
         questions.
      </p>
         <h2>GeeksforGeeks</h2>
         <p>GCET is an entrance test for the extensive classroom 
         programme by GeeksforGeeks to build and enhance Data 
         Structures and Algorithm concepts, mentored by Sandeep 
         Jain (Founder & CEO, GeeksforGeeks).He has 7 years of 
         teaching experience and 6 years of industry experience.
      </p>
      </div>
      <div class="middlediv">
         <h1>GeeksforGeeks</h1>
         <p>How many times were you frustrated while looking out
         for a good collection of programming/algorithm/interview
         questions? What did you expect and what did you get?
         This portal has been created to provide well written,
         well thought and well-explained solutions for selected
         questions.
         </p>
         <h2>GeeksforGeeks</h2>
         <p>GCET is an entrance test for the extensive classroom 
         programme by GeeksforGeeks to build and enhance Data 
         Structures and Algorithm concepts, mentored by Sandeep 
         Jain (Founder & CEO, GeeksforGeeks).He has 7 years of 
         teaching experience and 6 years of industry experience.
         </p>
      </div>
      <div class="rightdiv">
         <h1>GeeksforGeeks</h1>
         <p>How many times were you frustrated while looking out
         for a good collection of programming/algorithm/interview
         questions? What did you expect and what did you get?
         This portal has been created to provide well written,
         well thought and well-explained solutions for selected
         questions.
         </p>
         <h2>GeeksforGeeks</h2>
         <p>How many times were you frustrated while looking out
         for a good collection of programming/algorithm/interview
         questions? What did you expect and what did you get?
         This portal has been created to provide well written,
         well thought and well-explained solutions for selected
         questions.     
         </p>
      </div>
   </body>
</html>

Используя тег Div, мы можем закрыть пробел между тегом заголовка и тегом абзаца, в этом примере отобразится веб-макет из трех блоков.

Выход:

мы можем использовать CSS в любых подразделениях, используя следующие методы:

1. Использование класса:
мы можем использовать Class в этом конкретном div либо во внутреннем CSS, либо во внешнем CSS

  • In case of internal CSS: we need to define Class in the <head> section of HTML within <style> element.
  • In case of External CSS: we need to create a separate .css file and include it in HTML code in <head> section using <link> element.

    The class name should be different from other class names in other div otherwise the CSS used in one div can affect another division.

  • Code:
    <html>
       <head>
          <link rel="stylesheet" href="color.css">
          <title>
             gfg
          </title>
       </head>
       <body>
          <center>
             <div class="color">
                <!--open tag of Div!-->
                <caption>
                   <h1>GEEKSFORGEEKS</h1>
                </caption>
                <h1>Inline CSS is not  USED in THIS method.
                </h1>
             </div>
             <!--closing tag of Div!-->
          </center>
       </body>
    </html>
  • CSS for color class: File name color.css
    .color
    {
    height:400px;
    width:600px;
    border:1px solid;
    background-color: 009900;
    }

    In this example, we used a class to that particular Div. with name color.css which properties of div. It is a separate file which is linked by link tag in this HTML code

  • Output:

2. Inline CSS:
we can directly use CSS in div also this method does not require of CLASS. Div in HTML coding is used as a container tag also because it is the one that can contain all other tags.

  • Code:
    <html>
       <head>
          <title>
             gfg
          </title>
       </head>
       <body>
          <center>
             <div style="height:300px; width:500px; color:white;
                border:1px solid; background-color: 009900;">
                <!--open tag of Div!-->
                <caption>
                   <h1>GEEKSFORGEEKS</h1>
                </caption>
                <h1>Inline CSS is USED in THIS method.
                   In this div no class is used.
                </h1>
             </div>
             <!--closing tag of Div!-->
          </center>
       </body>
    </html>

    In this method, we applying inline CSS in the div tag. By using style attribute this style will apply to that particular div.

  • Output:



Разница между тегом 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 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.
Code:

<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>

Выход:

Поддерживаемый браузер: браузеры, поддерживаемые тегом <div>, перечислены ниже:

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