skip to Main Content

I do want to convert this to Tailwind

<div
  style={{
    width: 0,
    height: 0,
    borderLeft: "9px solid transparent",
    borderRight: "9px solid transparent",
    borderBottom: `8px solid  ${
      isCardExpired ? "rgb(250,77,86)" : "rgb(232,125,26)"
    }`,
    marginLeft: "auto",
    marginRight: "auto"
  }}
></div>

This will generate a triangle shape in CSS.

So far I tried to convert it like this

<div className="w-0 h-0 border-x-8 border-solid border-transparent mx-auto"></div>

How do I add this part

borderBottom: `8px solid  ${
  isCardExpired ? "rgb(250,77,86)" : "rgb(232,125,26)"
}`

This is my Code sandbox link

2

Answers


  1. You can use a utility like tailwind-merge or clsx like this:

    <div 
      className={
        clsx("w-0 h-0 border-x-8 border-solid border-transparent mx-auto", 
        isCardExpired 
          ? "border-[rgb(250,77,86)]" 
          : "border-[rgb(232,125,26)]")} 
    />
    
    

    You can also add the rgb colors to your theme for easier use:

    module.exports = {
      theme: {
        extend: { ... },
        colors:{
          custom1: 'rgb(12,159,100)',
          custom2: 'rgb(232,125,26)'
          ...
        }
      },
      plugins: [...],
    }
    

    And then use it as:

    <div 
      className={
        clsx("w-0 h-0 border-x-8 border-solid border-transparent mx-auto", 
        isCardExpired 
          ? "border-custom1" 
          : "border-custom2")} 
    />
    
    

    Edit: explanation of Tailwind border dimensions are here. You already have border-x-8 border-solid which is not part of the conditional, so it will work as you posted. If you need the width and height to be 8px, then you can change the border-x-8 to border-8. If as you stated only bottom then border-b-8 instead of border-x-8.

    Login or Signup to reply.
  2. You can use your code like in below example:

    <div className={`w-0 h-0 border-8 border-solid border-transparent mx-auto border-${isCardExpired ? '[rgb(250,77,86)]' : '[rgb(232,125,26)]' }`} ></div>
    

    However what you are trying to achieve is difficult through tailwind CSS, as Tailwind CSS is primarily designed for utility-first and atomic CSS classes. Complex border styling like the one you described might not be achievable with Tailwind classes alone. You will have to use like below

    function App() {
      const isCardExpired = true;
      const borderColor = isCardExpired ? 'border-red-600' : 'border-orange-500';
    
      return (
        <div className="flex justify-center">
          <div className={`w-0 h-0 ${borderColor} border-b-8`} style={{ borderLeft: '9px solid transparent', borderRight: '9px solid transparent' }}></div>
        </div>
      );
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search