В чем отличие тегов div и span
Перейти к содержимому

В чем отличие тегов div и span

  • автор:

Span VS Div HTML Tags – What is the Difference?

Kolade Chris

Kolade Chris

Span VS Div HTML Tags – What is the Difference?

If you inspect a web page with your browser’s developer tools, you’ll likely see a bunch of nested div tags, and possibly some content wrapped in a span tag.

Similar content is usually grouped together by these two container elements – span and div . You can use them both as containers, but they don’t work quite the same way.

In this tutorial, I will show you the differences between span and div so you won’t be confused by them anytime you have to use both.

The Key Differences Between span and div Tags

You can use both the span and div tags as a container if you want to make a particular part of the web page distinct and style it differently. But again, they don’t serve the exact same purpose.

The HTML div Tag

The div tag is a generic block-level element used for associating and grouping together a larger chunk of a web page – usually a section such as a header, footer, the main content, and so on.

In the example below, I group the header of a web page together with the div tag and styled it using CSS.

In the CSS below, I laid out the header and the navbar in it with CSS Flexbox. I also removed the default margin and padding assigned to elements by browsers.

header-with-div

In addition, you can use the div tag to group similar content together. This could be similar text, images, videos, and so on. So, you can always nest divs within divs, and attach unique classes or id attributes to them so you don’t get confused.

The HTML span Tag

The span tag is an inline element that you use to make a smaller part of content stand out with CSS or JavaScript. You shouldn’t nest span unless you thoroughly know what you’re doing – but you can put multiple span tags within a block-level element.

In the example below, I made some particular words stand out by wrapping span tags around them and styling them differently.

span-in-action

You can see the most important differences between the span and div tags in the table below:

span Tag div Tag
Inline-level element Block-level element
Used for grouping small chunks of text Used for grouping large chunks of texts together
Must not be nested to avoid confusion Usually nested

When should you use span or div ?

You should use span when you want to style a particular part of your content differently or manipulate it with JavaScript. You can also use it as a container for inline elements.

You should use the div tag, on the other hand, if you want to group large chunks of content together, and when you want to layout elements on the web page.

Conclusion

In this tutorial, you have learned about the differences between the span and div tags.

These tags are instrumental in styling and layouts. Just keep in mind that HTML5 introduced semantic elements such as section , header , nav , footer , and others. So in general, you should use either span or div only when the semantic elements don’t fit in with what you want to do.

Span vs. Div: The Difference Explained in 1000 Words or Less

Jamie Juviler

If you’re just starting to get the hang of HTML, you’ve probably learned how to use rudimentary HTML elements to build a page, such as <p>, <h1> and <h2>, <a>, and <image>.

three people in an office looking at a computer and learning the difference between span and div tags

These tags can be found all over the web. But, go to any big website, open the source code, and you might see something unfamiliar: a heap of nested <div> and <span> tags. If you’re not sure what these elements are for, it makes it tougher to understand how web pages are coded. And it doesn’t help that div and span do rather similar things.

Still, div and span elements are very common and probably used on most pages you visit. So, as a burgeoning website expert, you should know the difference between them if you want to grasp page structure and content. In this guide, we’ll show you what each one does and how you can apply them to your pages correctly.

Урок 12. Теги div и span

Урок 12. Теги div и span

Это двенадцатый заключительный урок изучения html, в котором вы узнаете про очень полезные блоки на странице, без которых было бы невозможно работать и верстать шаблоны для сайтов, про теги DIV и SPAN.

Теория и практика

В основном из данных двух тегов строится вся html страница. После того как вы поймете что можно делать с этими тегами, вы не будете знать как обходились раньше без них. По порядку о каждом из этих тегов.

Тег div

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

В коде html он выглядит следующим образом:

Вот так выглядит работа с тегом div. Он очень удобен. Сначала мы заключаем всё в блоки, а затем с помощью стилей(CSS) размещаем блоки как и где хотим.

Тег span

Тег span является строчным элементом, который предназначен для выделения фрагмента текста внутри других тегов, таких как <p> , <table> или <div> .

Пример кода с тегом span:

Данный тег работает следующим образом: вы помещаете в него тот фрагмент текста, который хотите выделить и задаете ему стиль.

Дело в том, что если для данных тегов стили не заданы, то вы не увидите никаких изменений на html странице. Стили задаются для тега div и span через таблицу стилей(CSS). В коде html вы только привязываете определенный стиль в CSS через атрибуты id="header" или class="warningText" . Данные атрибуты называются селекторами. Вы поймете как они работают когда начнете проходить уроки по CSS.

Пробуйте всё прописать руками. Тогда вы лучше запомните и будете помнить где и как их применить.

What is the difference between HTML div and span elements?

I would like to ask for some simple examples showing the uses of <div> and <span> . I’ve seen them both used to mark a section of a page with an id or class , but I’m interested in knowing if there are times when one is preferred over the other.

isherwood's user avatar

13 Answers 13

  • div is a block element
  • span is an inline element.

This means that to use them semantically, divs should be used to wrap sections of a document, while spans should be used to wrap small portions of text, images, etc.

For example:

Note that it is illegal to place a block-level element within an inline element, so:

EDIT: As of HTML5, some block elements can be placed inside of some inline elements. See the MDN reference here for a pretty clear listing. The above is still illegal, as <span> only accepts phrasing content, and <div> is flow content.

You asked for some concrete examples, so is one taken from my bowling website, BowlSK:

Ok, what’s going on?

Also note that HTML5 includes a broad new set of elements that define common page structures, such as article, section, nav, etc.

Section 4.4 of the HTML 5 working draft lists them and gives hints as to their usage. HTML5 is still a working spec, so nothing is «final» yet, but it is highly doubtful that any of these elements are going anywhere. There is a javascript hack that you will need to use if you want to style these elements in some older version of IE — You need to create one of each element using document.createElement before any of those elements are specified in your source. There are a bunch of libraries that will take care of this for you — a quick Google search turned up html5shiv.

Just for the sake of completeness, I invite you to think about it like this:

  • There are lots of block elements (linebreaks before and after) defined in HTML, and lots of inline tags (no linebreaks).
  • But in modern HTML all elements are supposed to have meanings: a <p> is a paragraph, an <li> is a list item, etc., and we’re supposed to use the right tag for the right purpose — not like in the old days when we indented using <blockquote> whether the content was a quote or not.
  • So, what do you do when there is no meaning to the thing you’re trying to do? There’s no meaning to a 400px-wide column, is there? You just want your column of text to be 400px wide because that suits your design.
  • For this reason, they added two more elements to HTML: the generic, or meaningless elements <div> and <span> , because otherwise, people would go back to abusing the elements which do have meanings.

There are already good, detailed answers here, but no visual examples, so here’s a quick illustration:

difference between div and span

<div> is a block tag, while <span> is an inline tag.

<div> is a block-level element and <span> is an inline element.

If you wanted to do something with some inline text, <span> is the way to go since it will not introduce line breaks that a <div> would.

As noted by others, there are some semantics implied with each of these, most significantly the fact that a <div> implies a logical division in the document, akin to maybe a section of a document or something, a la:

The real important difference is already mentioned in Chris’ answer. However, the implications won’t be obvious for everybody.

As an inline element, <span> may only contain other inline elements. The following code is therefore wrong:

The above code isn’t valid. To wrap block-level elements, another block-level element must be used (such as <div> ). On the other hand, <div> may only be used in places where block-level elements are legal.

Furthermore, these rules are fixed in (X)HTML and they are not altered by the presence of CSS rules! So the following codes are also wrong!

The significance of «block element» is implied but never stated explicitly. If we ignore all the theory (theory is good) then the following is a pragmatic comparison. The following:

That shows that not only should a div not be used inline, it simply won’t produce the desired affect.

As mentioned in other answers, by default div will be rendered as a block element, while span will be rendered inline within its context. But neither has any semantic value; they exist to allow you to apply styling and an identity to any given bit of content. Using styles, you can make a div act like a span and vice-versa.

One of the useful styles for div is inline-block

I have used inline-block to a great success, in game web projects.

Just wanted to add some historical context to how there came to be span vs div

History of span :

On July 3, 1995, Benjamin C. W. Sittler proposes a generic text container tag for applying styles to certain blocks of text. The rendering is neutral except if used in conjunction of a stylesheet. There is a debate around versus about readability, meaning. Bert Bos is mentioning the extensibility nature of the element through the class attribute (with values such as city, person, date, etc.). Paul Prescod is worried that both elements will be abused. He is opposed to text mentionning that "any new element should be on an old one" and adding "If we create a tag with no semantics it can be used anywehere without ever being wrong. We must force authors to properly tag the semantics of their document. We must force editor vendors to make that choice explicit in their interfaces."

From the RFC draft that introduces span :

First, a generic con- tainer is needed to carry the LANG and BIDI attributes in cases where no other element is appropriate; the SPAN ele- ment is introduced for that purpose.

DIV elements can be used to structure HTML documents as a hierarchy of divisions.

.

CENTER was introduced by Netscape before they added support for the HTML 3.0 DIV element. It is retained in HTML 3.2 on account of its widespread deployment.

In a nutshell, both elements arose out of a need for a more semantically-generic container. Span was proposed as a more generic replacement for a <text> element to style text. Div was proposed as a generic way to divide pages and had the added benefit of replacing the <center> tag for center-aligning content. Div has always been a block element because of its history as a page divider. Span has always been an inline element because its original purpose was text styling and today div and span have both arrived at being generic elements with default block and inline display properties respectively.

Div is a block element and span is an inline element and its width depends upon the content of it self where div does not

I would say that if you know a bit of spanish to look at this page, where is properly explained.

However, a fast definition would be that div is for dividing sections and span is for applying some kind of style to an element within another block element like div .

Manohar Reddy Poreddy's user avatar

Pablo Herrero's user avatar

In HTML there are tags that add structure or semantics to content. For example the <p> tag is used to identify a paragraph. Another example is the <ol> tag for an ordered list.

When there is no suitable tag available in HTML as shown above, the <div> and <span> tags are usually resorted to.

The <div> tag is used to identify a blocklevel section/division of a document that has a line break both before and after it.

Examples of where div tags can be used are headers, footers, navigations etc. However in HTML 5 these tags have already been provided.

The <span> tag is used to identify an inline section/division of a document.

For example a span tag can be used to add inline pictographs to an element.

Robert's user avatar

Remember, basically and them self doesn’t perform any function either. They are not specific about functionality just by their tags.

They can only be customized with the help of CSS.

Now that coming to your question:

SPAN tag together with some styling will be useful on having hold inside a line, say in a paragraph, in the html. This is kind of line level or statement level in HTML.

DIV tag functionality as said can only be visible backed with styling, can have hold of large chunks of HTML code.

DIV is Block level

Both have their time and case when to be used, based on your requirement.

Hope am clear with the answer. Thank you.

yatheendra k v's user avatar

Semantics

Both span and div are elements with no associated semantics. They can be used when you need an element (e.g. for styling or targetting with JavaScript) but there is no element in HTML which has suitable semantic meaning for the content.

Styling

Neither element is heavily styled by browser’s built-in stylesheets. The key difference is the display property. span elements default to display: inline while div elements default to display: block .

Structure

span and div elements are allowed in different places in an HTML document.

You’ll see many earlier answers here refer to them as being "inline elements" and "block elements". This was a distinction made by HTML 4 and is now out of date (although useful as a general guideline). (There’s a strong, but not 100%, correlation between elements HTML 4 defined as inline or block and the default CSS display property value.)

HTML 5 takes a more nuanced approach to defining which elements are allowed where.

The span element can be used "Where phrasing content is expected" and can contain "Phrasing content".

Meanwhile, the div element can be used "Where flow content is expected" (in which case it can contain "flow content") and "As a child of a dl element" in which case it can contain "one or more dt elements followed by one or more dd elements, optionally intermixed with script-supporting elements").

It’s quite a lot more complex that the HTML 4 view of things, but the specification is well hyperlinked and a validation service is available.

You can use the block/inline distinction as a general guideline. If you need to generate new lines, or wrap content that does (like p aragraphs, table s, article s, and section s) you probably should be using a div . If you have content that flows together in a line (like words) then you probably should be using a span . (Assuming there isn’t a suitable semantic element, of course).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *