Search code examples
cssruby-on-railstailwind-cssfield-with-errors

field_with_error not triggering Tailwind CSS style


In a Rails 7 app with Tailwind CSS installed, I am using this form:

<%= form_with(model: project) do |f| %>
    <%= f.label :name, class: "some_tailwind_css_class" %>
    <%= f.text_field :name, autofocus:true, class: "some_other_tailwind_css_class" %>
    <%= f.submit class: "yet_another_tailwind_css_class"  %>
<% end %>

When there is no error in the form, the Tailwind CSS classes are triggered as expected, and the styles are perfectly applied to the HTML.

However, when the form throws a validation error (let's say: the name field is empty), I am unable to apply the Tailwind CSS classes for fields with errors (red border, red text for instance), given that the field_with_error class is nowhere to be found in the new.html.erb view file (as it is generated by the form helper instead).

I tried updating application.tailwind.css as follows, but I am unable to get that style triggered by the field_with_error classes in the HTML no matter what:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer components {
  .field_with_errors {
    label {
      @apply text-red-900;
    }
    input, textarea, select {
      @apply border-red-300 text-red-900 placeholder-red-300;
    }
  }
}

My concern is that, since Tailwind CSS scans the source code to determine what CSS to compile (or not, for that matter), it may not be "seeing" any HTML code actually containing field_with_errors, and is therefore not loading the custom CSS classes added to application.tailwind.css.

Is this not the way to proceed with Rails & Tailwind? Is there an error in the CSS I included in application.tailwind.css? Or is there another issue I am missing?


Solution

  • the correct syntax should be

    @tailwind base;
    @tailwind components;
    @tailwind utilities;
    
    div.field_with_errors > label {
      @apply text-red-900;
    }
    
    div.field_with_errors > :is(input, textarea, select) {
      @apply border-red-300 text-red-900 placeholder-red-300;
    }
    
    

    problem is you try to modify base element instead component

    you need to use @layer base instead @layer component the explanation are here

    and also

    because the .field_with_errors is added dynamically to the webpage

    and tailwind css doing tree-shaking when compiling, it will try to remove all custom css that is not used

    therefore .field_with_errors will be removed thus why the css is not applied

    to make it stay we could declare the class without using @layer as per this guide