Fine grained control over your styles in 3 steps
The Problem
I wanted to increase the sizes of the images in my personal site’s projects page. So I wrote some styles in globals.css
, and applied it to the parent node that contains the content.
This style applies to all images within elements with the classes .prose
and .project
.
.prose.project img {
@apply max-w-none rounded-md border border-secondary bg-tertiary md:rounded-lg lg:-ml-16 lg:w-[calc(100%+128px)];
}
The problem arises with this dynamic classlg:w-[calc(100%+128px)]. It adds 128 pixels to 100% of the parent element’s width. This is a common technique in CSS for achieving responsive and dynamic layouts.
This made the images in one of my custom MDX components to blow out of proportions.
I don’t want this global style to be applied. How do I go about excluding it?
The Solution
The key to solving this problem lies in understanding how CSS selectors work and how to leverage them to target specific elements. In our case, we want to exclude the global style from one specific element.
Step 1: Add a Custom Class to the component
First, add a custom class to the element/component where you don’t want the global style to be applied. For example, you can add a class named .no-prose-style
.
<div
className="project prose animate-in no-prose-style"
style={{ "--index": 2 } as React.CSSProperties}
>
Step 2: Define the Override Styles in CSS
Next, define the styles you want to override or reset for the .no-prose-style
class in your CSS. You can reset the properties to their default values or set them to something else as needed.
In my case, the problem revolved around images blowing out of proportions in my custom component. Hence, I set the width on large screens to be 100% with a Tailwind utility class.
.no-prose-style img {
@apply lg:w-full;
}
The result:
In conclusion, by understanding CSS selectors and utilizing targeted overrides, we can maintain fine-grained control over our styles in Tailwind CSS. With just a few simple steps, we can exclude global styles from specific elements, ensuring a more tailored and cohesive design across our projects.
Footnotes:
GitHub: https://github.com/phukon
Socials: https://rkph.me
Top comments (0)