In the previous article, we learned that every HTML element has a default display value, which depends on the type of element it is. The default display value for most elements is either block or inline.
The CSS display property is used to override the default display behavior of HTML elements.
Recap of previous Article:
- A block-level element starts a new line in the layout and extends horizontally from its starting point to the leftmost and rightmost edges of its containing element or parent container.
- An inline element does not start on a new line and only occupies the necessary width.
CSS Display Syntax
Below is the syntax for adding display property:
Selector {
display: value;
}
- The selector can be any one or more of those discussed previously in CSS Selectors.
- "display" is the property key
- "value" can be in inline, block, inline-block, table, none, flex, grid, etc.
How to over ride default display of an HTML Element
You can override the default display behavior of HTML elements using the CSS display property.
Playground Example: To make things simpler, you can click the button below to open the playground, which comes with pre-filled HTML and CSS.
In the editor, you will see HTML, CSS, and JS input on the left/top, and the output on the right/bottom.
As noted in a previous article, the default display of the span element is inline. However, we can override this using the display property.
Add the display property as shown below, and you'll notice that the span element moves to a new line.
Example:
/* css Display */
.span {
display: block;
}
Below is the list of common display property values and their applications.
Value | Application |
---|---|
block | Set the display as block, the element take a new line |
inline | Set the display as inline, the element will be on the same line if there is space |
inline-block | Set the display as inline-block. In contrast to block, the element will be on the same line if there is space. In contrast to inline, the element will respect the width, height, marging and padding values |
none | Element will not be visible in the UI |
flex | Used in flex-box |
grid | Used in Grid layout |
Want to practice more? Click here for more hands-on exercise.
References: