CSS Display Property
The CSS display property is one of the most fundamental properties in CSS. It controls how an element is displayed on a webpage and how it interacts with other elements.
Purpose:
-
- The display property determines the box type of an element, affecting its layout and rendering.
- It controls whether an element is treated as a block-level element, an inline element, or something else entirely.
Common Values:
-
block:
- The element generates a block-level box, meaning it takes up the full width available and starts on a new line.
- Examples: <div>, <p>, <h1> to <h6>, <form>, <section>.
-
inline:
- Inline element generates an inline-level box, meaning it only takes up as much width as necessary and does not start on a new line.
- Examples: <span>, <a>, <img>, <strong>, <em>.
-
inline-block:
- The element generates an inline-level box but also allows you to set its width and height, like a block-level element.
- It’s a combination of inline and block.
-
none:
- The element is completely removed from the document flow and is not displayed.
- It’s useful for hiding elements dynamically with JavaScript.
-
flex:
- Flex element generates a block-level flex container, enabling the flexbox layout model.
- Used for creating flexible and responsive layouts.
-
grid:
- The element generates a block-level grid container, enabling the grid layout model.
- Used for creating complex, two-dimensional layouts.
Example:
-
Block Element:
div {
display: block;
width: 200px;
height: 100px;
background-color: lightblue;
}
The div will take up the full width of its parent container and start on a new line.
-
Inline Element:
span {
display: inline;
background-color: yellow;
}
This span will only take up the width of its content and will not start on a new line.
-
Inline-Block Element:
.inline-block-example {
display: inline-block;
width: 150px;
height: 50px;
background-color: lightgreen;
}
The element will be laid out inline but can have its width and height set.
-
Hiding an Element:
.hidden {
display: none;
}
This element with the class hidden will not be displayed.
-
Flexbox Layout:
.flex-container {
display: flex;
justify-content: center;
align-items: center;
}
The element with the class flex-container will become a flex container, allowing you to easily align and distribute its children.
-
Grid Layout:
.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 10px;
}
The element with the class grid-container will become a grid container, allowing you to create a grid layout with three columns.