Webdev

CSS display Property

The CSS display property is one of the most important properties in CSS, as it controls the layout behavior of an element. It specifies how an element should be rendered on the page, whether it’s a block, inline, or another layout type. The display property affects how elements interact with each other in terms of spacing, alignment, and overall layout flow.

Syntax

element {
  display: value;
}

Where value can be one of several options that determine the element’s layout behavior.

Common Display Values

  1. block
  2. inline
  3. inline-block
  4. flex
  5. grid
  6. none
  7. table, table-row, table-cell

1. display: block;

div {
  display: block;
  background-color: lightcoral;
}

2. display: inline;

span {
  display: inline;
  background-color: lightgreen;
}

3. display: inline-block;

div {
  display: inline-block;
  width: 150px;
  height: 100px;
  background-color: lightblue;
}

4. display: flex;

.container {
  display: flex;
  gap: 20px;
}

.item {
  background-color: lightseagreen;
  padding: 20px;
}

5. display: grid;

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.item {
  background-color: lightgoldenrodyellow;
  padding: 20px;
}

6. display: none;

div {
  display: none;
}

7. display: table;, display: table-row;, display: table-cell;

.container {
  display: table;
  width: 100%;
}

.row {
  display: table-row;
}

.cell {
  display: table-cell;
  padding: 10px;
  border: 1px solid black;
}

Other display Values

  1. inline-flex: Behaves like flex, but the flex container remains inline, allowing other inline elements to flow around it.
    .container {
      display: inline-flex;
    }
    
  2. inline-grid: Behaves like grid, but the grid container remains inline.
    .container {
      display: inline-grid;
    }
    
  3. list-item: Behaves like a block element, but also adds a list-item marker (like bullets in a <ul>).
    li {
      display: list-item;
    }
    
  4. run-in: Rarely used, it makes an element either behave as a block or inline element, depending on the surrounding context.

display: Inline vs Block vs Inline-Block Comparison

Block Elements:

Inline Elements:

Inline-Block Elements:

<div style="display:block">Block element</div>
<div style="display:inline">Inline element</div>
<div style="display:inline-block">Inline-block element</div>

Conclusion

The display property in CSS is essential for controlling how elements are rendered on the page and how they interact with each other. Understanding the various display values helps in creating complex layouts, aligning items, and optimizing user interface responsiveness. Whether it’s using block-level elements, inline elements, or more modern layouts like flex and grid, the display property is key to controlling layout structure in web design


next -> Css Positions

go back