Understanding CSS Display Property: A Guide with Examples | Code With Tanveer
Cascading Style Sheets (CSS) is a crucial part of web development, enabling designers to control the layout and presentation of their HTML documents. One key aspect of CSS is the `display` property, which determines how an element is rendered on the web page. Let's delve into the different values of the `display` property and explore examples of each.
1. Block-level Elements
By default, HTML elements are considered block-level. This means they start on a new line and take up the full width of their container. The `display: block;` property explicitly sets an element to be a block-level element.
.block-example {
display: block;
width: 200px;
height: 100px;
background-color: #3498db;
color: #ffffff;
}
<div class="block-example">
This is a block-level element.
</div>
2. Inline Elements
Inline elements, on the other hand, do not start on a new line and only take up as much width as necessary. The `display: inline;` property is used to make an element inline.
.inline-example {
display: inline;
background-color: #2ecc71;
color: #ffffff;
padding: 5px;
}
<span class="inline-example">This is an inline element.</span>
3. Inline-Block Elements
Combining aspects of both block and inline elements, the `display: inline-block;` property allows an element to be inline, yet it can have a width and height set.
.inline-block-example {
display: inline-block;
width: 150px;
height: 75px;
background-color: #e74c3c;
color: #ffffff;
}
<div class="inline-block-example">
This is an inline-block element.
</div>
4. None (Hiding Elements)
Setting `display: none;` hides the element from the page entirely. This is commonly used for conditional display or animation effects.
.hidden-example {
display: none;
}
<p class="hidden-example">This paragraph is hidden.</p>
5. Flexbox
The `display: flex;` property introduces a powerful layout model, allowing for flexible and responsive container layouts.
.flex-container {
display: flex;
justify-content: space-between;
}
.flex-item {
width: 100px;
height: 100px;
background-color: #f39c12;
color: #ffffff;
}
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
Understanding and utilizing the `display` property in CSS opens up a realm of possibilities for creating well-structured and visually appealing web layouts. Experiment with these examples to enhance your understanding of how different values impact the display of HTML elements on your web page.
0 Comments