CSS for Web Development

0% completed

Previous
Next
Block, inline, and inline-block

In CSS, the display property determines how elements are rendered on the page. The three most common display types are block, inline, and inline-block. Each type affects the layout, flow, and behavior of the elements. Understanding these display types helps you structure your page content effectively.

  • Block elements occupy the full width available, start on a new line, and can have margin and padding.
  • Inline elements only take up as much width as necessary, sit within the text flow, and typically do not accept vertical margins and padding.
  • Inline-block elements combine the characteristics of both block and inline elements. They flow inline like inline elements but allow setting width, height, margin, and padding like block elements.

Syntax

Follow the code block below to set the display property in CSS:

/* Set element as block */ display: block; /* Set element as inline */ display: inline; /* Set element as inline-block */ display: inline-block;

Explanation:

  • display: block;
    • The element starts on a new line and takes up the full width of its container.
  • display: inline;
    • The element flows with text and only takes up the necessary width.
  • display: inline-block;
    • The element flows with text like inline elements but also accepts box model properties like block elements (e.g., width, height, margin, padding).

Example 1: Block and Inline Elements

In this example, we demonstrate the difference between block and inline elements using <div> for block and <span> for inline.

HTML

. . . .

Explanation:

  • Block Element:
    • The <div> with the class .block-element takes up the full width and starts on a new line.
  • Inline Element:
    • The <span> with the class .inline-element only occupies the space it needs and flows with the surrounding text.

Example 2: Inline-Block Element

In this example, we style elements as inline-block to show how they combine the traits of both block and inline elements. Multiple inline-block elements can sit next to each other, but they also allow you to set dimensions and spacing.

HTML

. . . .

Explanation:

  • Display as Inline-Block:
    • Each <div> with the class .inline-block-element can sit on the same line, similar to inline elements.
  • Control Over Dimensions:
    • The width, height, margin, and padding can be explicitly set, just like block elements.
  • Outcome:
    • The inline-block elements appear side by side, maintaining their box dimensions while still flowing inline with text if needed.

This lesson shows you how to use the display property with block, inline, and inline-block values to control element layout. Using these properties effectively will help you build flexible and organized page structures.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next