乐闻世界logo
搜索文章和话题

How to use custom percentages in padding in TailwindCSS?

2个答案

1
2

When using Tailwind CSS, you can create custom percentage-based padding utility classes by extending its default theme in the tailwind.config.js file. Tailwind already provides a set of predefined padding utility classes, but if you need to use specific percentage values for padding, you can follow these steps:

  1. Open your project's tailwind.config.js file.
  2. Navigate to the theme section.
  3. Extend the padding property to include the percentage values you want to use.

Here is a specific example:

javascript
// tailwind.config.js module.exports = { theme: { extend: { padding: { '5p': '5%', // Creates a utility class named 'p-5p' for 5% padding '10p': '10%', // Creates a utility class named 'p-10p' for 10% padding // You can add more custom percentages here } } }, variants: {}, plugins: [], }

In the above configuration, we've added two custom padding percentage classes: p-5p and p-10p. Now, you can use these classes in your HTML just like any other Tailwind utility classes.

For example:

html
<div class="p-5p bg-gray-200">This box has 5% padding</div> <div class="p-10p bg-gray-300">This box has 10% padding</div>

In the above HTML code, the first div will have padding equal to 5% of its width, and the second div will have padding equal to 10% of its width.

Note that when adding custom configurations, it's best to follow Tailwind's naming conventions, such as p-{size} for padding and m-{size} for margin, to maintain consistency and predictability. Additionally, ensure that your tailwind.config.js file is correctly imported and processed during the build process to generate the appropriate CSS.

2024年6月29日 12:07 回复

For Tailwind, you don't need to escape the percentage sign; it handles this automatically. Here's a live example: https://play.tailwindcss.com/CYR6JOXYyz?file=config

js
theme: { extend: { spacing: { '80%': '80%', // p-80% - works as expected } }, }

The class .p-80% will be generated by Tailwind for the above configuration.

2024年6月29日 12:07 回复

你的答案