Tuesday, July 23, 2024
HomeCSSUse Circumstances For CSS fit-content

Use Circumstances For CSS fit-content


On this quick article, we’ll discover some use-cases for CSS fit-content. In case you’re new to CSS intrinsic sizing, I wrote about it intimately in this text.

Let’s dive in!

Introduction

The key phrase fit-content will make a component width equal to its content material based mostly on particular circumstances.

Here’s a move chart that exhibits how the browser offers with it.

It checks if the accessible is greater than max-content, then the width is the same as max-content. If the accessible area is lower than max-content, then the width will probably be equal to the accessible area. Lastly, if the accessible area is lower than min-content, then the width will probably be equal to min-content.

Use instances for fit-content

Intrinsic headline

Have you ever ever wanted a option to middle a headline and add a customized underline just for the content material and never the entire factor?

We will try this by wrapping the heading content material in a span after which making use of the underline on it.

<h1><span>Headline content material</span></h1>
h1 span {
   box-shadow: inset 0 -6px 0 0 lightgrey; 
}

With fit-content, that is not wanted.

h1 {
    width: fit-content;
    margin-left: auto;
    margin-right: auto;
    box-shadow: inset 0 -6px 0 0 lightgrey;
}

Demo

Determine and picture

Inside an article physique, we would must have a <determine> take its content material width, and never exceed that if it’s too giant.

Utilizing fit-content is ideal for that.

determine {
    width: fit-content;
    margin: 0 auto;
    background: #fff;
    padding: 1rem;
    border-radius: 10px;
}

Demo

Intrinsic Content material Block

That is one in every of my favorites. Inside an article physique, we would like a particular content material block to be equal to its content material.

Within the following determine, we’ve got a “Associated article” widget that is the same as its contents.

.article-body .related-widget {
    width: fit-content;
}

Intrinsic Tabs

That is an attention-grabbing use-case that I noticed in Google Advertisements. The concept is that we would like the tab factor to be clickable solely on its content material.

Within the following determine, discover how the highlighted space represents the tab’s content material.

.tab-item {
    flex-grow: 1;
    width: fit-content;
}

I hope you discovered this text helpful. Thanks for studying!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments