Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align input and label from collection_check_boxes?

I am using collection_check_boxes and have problems with aligning checkbox and text. This is my code:

<div class="col-md-4">
  <%= f.collection_check_boxes :dog_ids, Dog.all, :id, :name %>
</div>

Form is displayed like this:

[checkbox1]
  text1

[checkbox2]
  text2

[checkbox3]
  text3

I am trying to align input and label but didn't have success. I have seen these question but it don't work for me: Align checkboxes for f.collection_check_boxes with Simple_Form

I want to accomplish this:

[checkbox1] text1

[checkbox2] text2

[checkbox3] text3

Thank you for your help!

like image 250
Cristiano Avatar asked Jun 08 '14 18:06

Cristiano


People also ask

How do I get a checkbox and label on the same line?

Method 1: By making the position of checkbox relative, set the vertical-align to the middle can align the checkboxes and their labels.

How do I change the position of a checkbox in HTML?

Float the checkbox to the right and the label to the left, and set the label position to absolute. If you just put the label text to the right of the box without a label, it will not cause the checkbox to be checked when clicked.

How do I align a checkbox horizontally?

Set the checkbox horizontally by including the data-type = "horizontal" to the fieldset. You can select the checkbox button more than one at a time.

How do I move a checkbox to the left in HTML?

Also you can use float:left CSS property to set the checkboxes left side.


1 Answers

The definition for collection_check_boxes:

collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)

The last argument permits you to do something like this: (this does exactly what you want using collection_check_boxes)

<%= f.collection_check_boxes(:dog_ids, Dog.all, :id, :name) do |b| %>
  <div class="row">
    <%= b.label(class: "check_box") do %>
      <div class="col-xs-4">
        <%= b.check_box(class: "check_box") %>
      </div>

      <div class="col-xs-8">
        <%= b.object.name %>
      </div>       
    <% end %>
  </div>
<% end %>

Read more about collection_check_boxes

There is another method too: style your checkbox input and your label from css.

For a better css specificity I will add a new class named 'checkbox-list' to:

<div class="col-md-4 checkbox-list">
  <%= f.collection_check_boxes :dog_ids, Dog.all, :id, :name %>
</div>

.checkbox-list input[type="checkbox"] {
  display: inline-block;
  width: 10%;
}

.checkbox-list input[type="checkbox"] + label {
  display: inline-block;
  margin-left: 10%;
  width: 80%;
}
like image 199
cristian Avatar answered Oct 21 '22 02:10

cristian