Skip to main content

Display

The display property in CSS is a fundamental property that controls the layout behavior of an element within the document flow. It determines how an element should be displayed and how it interacts with other elements in the layout. Understanding the display property is crucial for anyone involved in web development, especially for roles that require a deep understanding of how elements are rendered on the page.

Block

Elements with display: block; take up the full width available, with a new line before and after the element. Examples include <div>, <p>, and <h1>.

div {
display: block;
}

Inline

Elements with display: inline; take up only as much width as necessary and do not force new lines. Examples include <span>, <a>, and <strong>.

span {
display: inline;
}

Inline-Block

Elements with display: inline-block; are similar to inline elements but can have a width and height.

.box {
display: inline-block;
width: 100px;
height: 100px;
}

None

Elements with display: none; are removed from the document flow and not displayed at all.

.hidden {
display: none;
}

Flex

Enables the flexbox layout on an element, allowing you to design complex layout structures with a more predictable way than traditional models, especially when you're dealing with complex layouts and when your items are of different sizes.

.container {
display: flex;
}

Grid

Enables the grid layout, providing a more rigid and controlled way to design layouts with rows and columns.

.container {
display: grid;
}

Table

Makes the element behave like a table element, useful for tabular data or mimicking table behavior.

.table {
display: table;
}

Special Display Values

Contents

The element itself will not be rendered, but its children and pseudo-elements will be as normal. This is useful for removing wrapper divs.

.wrapper {
display: contents;
}

List-Item

Makes the element behave like a list item, often used with ::before to generate counters or bullets.

.custom-list {
display: list-item;
}

Best Practices

  1. Use Semantic HTML: Whenever possible, use HTML elements that naturally correspond to the display value you intend to apply.

  2. Avoid display: none for Accessibility: Elements with display: none are ignored by screen readers. Use other methods to hide content if it should still be accessible.

  3. Leverage Modern Layouts: For complex layouts, prefer using Flexbox and Grid as they offer more control and are designed for building complex layouts.

  4. Be Mindful of Document Flow: Changing the display value can remove an element from the normal document flow, affecting the layout of other elements. Always test thoroughly.

Understanding the display property can significantly impact how you approach layout design, making your CSS more efficient and maintainable.

The MDN document for display proeprty