How to keep a checkbox and label on the same line in a Rails form?
According to the bootstrap wiki, it must be
<label class="checkbox">
<input type="checkbox"> Check me out
</label>
which in Ruby on Rails is
<%= f.label :terms_of_service do %>
<%= f.check_box :terms_of_service %>
I agree to the <%= link_to 'Terms of Service', policies_path %>.
<% end %>
It looks like you're using Bootstrap, so I recommend adapting your view code to use the horizontal form layout described in this section of the Bootstrap docs: https://getbootstrap.com/docs/4.3/components/forms/#horizontal-form
<br>
<%= f.check_box :terms_of_service, :style => "float:left;" %>
<%= f.label :terms_of_service, "I agree to the #{link_to 'Terms of Service', policies_path}.".html_safe, :style => "float:left;" %>
<br>
The comment on the answer is correct, but it assumes some nuance of understanding about order of elements.
The correct answer is as follows:
<%= f.check_box :terms_of_service %>
<%= f.label :terms_of_service, "I agree to the #{link_to 'Terms of Service', policies_path}.".html_safe
, {class: "checkbox inline"} %>
Two things are necessary:
- The class on the label element
- The checkbox element has to be before the label element.
This is obvious once you see it working, but all the other samples for form_for always have the inputs after the labels and you need to change that up for checkbox.
<div class="form-inline">
<%= f.check_box :subscribed, class: 'form-control' %>
<%= f.label :subscribed, "Subscribe" %>
</div>