3

I have a Rails app where I am using custom stylesheets that have no effect on the <form> tags generated by the Rails form_tag helper. Can someone point me to some code or an example that shows how to add CSS styles to a form_tag?

3 Answers 3

5
<% form_tag {:controller => 'my_controller', :action => 'my_action'}, :id => 'my_id' do %>

in .css file

#my_id {
 /* your style */
}
Sign up to request clarification or add additional context in comments.

1 Comment

or use :class => 'my_class' on all forms
0

With the form_for helper, the first argument you pass is used exclusively by the url_for helper to determine what URL to submit the form to. Hash-style named arguments are treated as a single argument (a hash) by Ruby, so if you pass a set of options as your first argument (e.g. form_tag(controller: 'my_controller', action: 'show')), any additional options you include (like :method or :class) will be treated as options to url_for instead of to form_for, which isn't what you want.

To fix this, you can explicitly pass a hash as the first argument to form_tag, and put your other options (such as the class attribute, which is probably what you'll want to use for styling) outside of that hash, like so:

<% form_tag {controller: 'my_controller', action: 'show'}, class: 'main-form' do %>
  <!-- Form content here -->
<% end %>

After that, you can use css to style your form as you would with any other element:

.main-form {
  // Style rules here
}

For more information on the options form_for accepts, see the docs for form_for and url_for.

Comments

-3

Few ways you can do this:

form {
  color: red;
}

This will grab ALL forms and style them.

#id {
  color: red;
}

This will grab the forms that match the ID and style them.

.class {
  color: red;
}

This will grab the forms that match the class and style them.

1 Comment

He ask how to add class or id to form_for, not how to style it in css.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.