A few simple, yet powerful macros that add flexible styling to your formtastic forms.
First we will need to install Haml — Yes even you ERB enthusiasts who wont drink the Haml-Aid need to get on the Sass track if you are serious about productivity and DRYness. Sass kicks ass!
gem install haml cd my_rails_app haml --rails
1. Set up a master Sass file and include it in your layout
2. Drop this file in the same directory as your master.sass
3. Include this file at the top of that sheet with:
@import formtastic_base.sass
If you haven’t already, you should also install Formtastic
Done! Are you ready to churn out beautiful forms in SECONDS?
Let’s rock…
Once you have created semantic forms with formtastic, you can use the default style like this:
form.formtastic +formtastic
Finished! Wow, that was tough – go take a coffee break and come back later :D
Can be modified in formtastic_base:
!total_width=100%
!label_width=24%
!input_width=70%
!label_pad=2%
- “left” = labels floated left and text-align left
- “right” = labels floated left and text-align right
- “clear” = labels above inputs
!label_float="left"
!button_float="left"
Note: Do not mix units (em px %) as it will break the calculations.
Percentages will yield elastic forms.
As for other defaults (color, fonts, etc), the file is well-commented
In order to set the basic layout, you don’t need to even touch the defaults.
form.formtastic +formtastic(510px,100px,400px,8px,"right","left")
Sweet!
Note: When using floated labels (left or right), it’s good to give your form !total_width a little leeway (add 10px or 5% minimum) to keep those floats intact.
You can align labels with error messages so they read like sentences.
Create formtastic.rb in config/initializers and add this:
Formtastic::SemanticFormBuilder.inline_order = [:errors, :input, :hints]
This is best used with right-aligned labels
form.formtastic
+formtastic(100%,20%,70%,4%,“right”)
You will need to provide a margin-top value to align labels with error messages, there is a convenient mixin for that
form.formtastic +formtastic(100%,20%,70%,4%,"right") +formtastic-errors-on-top(21px)
The value must be adjusted until label and error message line up.
Thanks to the misbehavior of legend tags, a tweaks is needed for Safari. Just set a pixel or em width on the legend’s span like this
form.formtastic +formtastic +formtastic-safari-hack(120px)
Internet Explorer is not yet supported. Patches are welcome.
Overall this is still very alpha so please test across browsers before using in production.
Enjoy!