Divs and Spans

The div and span tags are made for CSS. A div is a section or a ‘division’ in a web page. A div can be thought of as a block. On the other hand, a span is used to group inline elements in an HTML web page. For example, a span could be used to change the style of just a few words from a paragraph or heading.

Divs and spans are unnoticed and do not change the way a page displays until you use CSS to apply styles to them. If a div or span exists in a HTML document but no style is applied to it in a CSS style sheet, then the appearance of the web page will not change.

Take a look at the example below. A div contains a line of text and some of that text is within a span. This means the text in the div can have a specific style (eg. green background and border), while text inside the span (which is inside the div) can have a different style (eg. light blue background and red border).

Screen Shot 2017-04-14 at 4.27.21 pm

The video below shows how to add divs and spans to a web page. It also shows how to change the border, background colour, width and height of a div; and how to change the text colour, background colour and text decoration inside span tags. Scroll further down to see the sample code.

The HTML code below shows how to add divs and spans. Note that the HTML code references an external CSS style sheet. Make sure you make a CSS file and give it the same name as the reference in the HTML file. The CSS file in this example is called stylesheet.css.

<!DOCTYPE html>
<html>
<head>
 <title>Div and Span</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet3.css" type="text/css"/>
</head>
 
<body>
 <div>
 <h1>This is a heading</h1>
 <p>This <span>is a</span> paragraph</p>
 </div>
</body>
 
</html>

The CSS code below shows how to specify the width and height of a div and how to add borders and background colours to divs, and text colour, decorations, and background colours to spans.

div{
 border:2px solid #00FF00; /* green */
 background-color:#FFFF00; /* yellow */
 width: 400px;
 heigth: 200px;
}
span{
 color:#2E64FE; /* blue */
 background-color:#FFFFFF; /* white */
 text-decoration:underline;
}