html

CSS width fit content

CSS width property defines the width of the element’s content area. This area is the space between an element’s border, padding, and margin. Moreover, the CSS width property with the value “fit-content” will adjust the width of the element according to the content.

This study will explain the CSS width property with the value fit-content.

How to Use CSS width Property With fit-content Value?

For the purpose of using CSS width property with fit-content value, check out the given syntax:

width: fit-content

 
Example

In HTML, add three div elements with the same class name “box” and three different classes “color-1”, “color-2”, and “color-3”, respectively. Add <p> element inside each div to add content to the web page:

<div class="box color-1">
    <p>CSS width fit content</p>
</div>
<div class="box color-2">
    <p>Hello World!</p>
</div>
<div class="box color-3">
    <p>Teamwork begins by building trust. We are a team working for a common mission. </p>
</div>

 
Here is the output of the HTML code:


So far, we have discussed the HTML page. Now, in the next section, we will apply different CSS styles to the HTML elements to make them look better. In the ongoing example, we will check out the behavior of the “width” property having the value “fit-content” in the CSS.

Style “box” div

.box {
    width: fit-content;
    height: 50px;
    color: ghostwhite;
    padding: 6px;
    margin: 2px;
    font-size: 18px;
}

 
The “.box” refers to the div class box. Below are the properties that are applied to it:

    • width” property with the value “fit-content” uses the available space, but it will not exceed the content.
    • height” is the property that determines the element’s height.
    • color” defines the element’s font color.
    • padding” property produces space inside the element’s border or around the content.
    • margin” determines space around the element.
    • font-size” property determines the font size.

Style “color-1” div

.color-1 {
    background-color: #00ABB3;
}

 
The “background-color” property is set to the “.color-1” div.

Style “color-2” div

.color-2 {
    background-color: #083AA9;
}

 
Style “color-3” div

.color-3 {
    background-color: #4C6793;
}

 
It can be observed that the width of the element is set equal to the content:


That’s great! We have successfully learned the usage of the CSS “width” property with the value “fit-content”.

Conclusion

The CSS width property allows us to utilize several values. These values are in percentage, pixels, or more. To set it according to the content, the “fit-content” value can be set. This post has described the CSS width property with the value fit-content with a practical demonstration.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.