Div vs. Span: Understanding the Basics

The <div> and <span> elements are often used to group content together, but they have different purposes.

The <div> Element

The <div> tag is a block-level element, which means it takes up the entire width of its container and starts on a new line. It is typically used to group larger chunks of content and create page layouts.

This content is inside a <div> element

By using <div> elements, you can define different sections of your page. For example, this content is inside a container that has a border around it, making it easier to distinguish visually.

The <span> Element

The <span> tag is an inline element, which means it only takes up as much width as necessary and does not force content onto a new line. It is commonly used to style small parts of text or group inline elements.

For example, you can highlight text using the <span> tag, as shown here.

Introducing CSS

CSS (Cascading Style Sheets) is used to control the presentation and layout of HTML elements. You can apply styles directly within the HTML file, like in the example above, or link to an external CSS file.

Using CSS, you can change the appearance of your <div> and <span> elements by setting properties like background-color, font-size, margin, and more.

Example CSS Styles


/* Highlight text */
.highlight {
  background-color: yellow;
}

/* Container with a border */
.container {
  border: 1px solid black;
  padding: 10px;
  margin: 10px;
}
    
Next: CSS Styling: Table of Contents Previous: ID and Anchors