Posted almost 10 years ago. Visible to the public.

Center a float horizontally

Note: We have card with all CSS centering options. You probably want to head over there and get an overview over what techniques are available for your use case and browser requirements.


If you cannot use display: inline-block, centering a float can be useful if you want to center something and at the same time make its width automatically fit some content.

Use this SASS:

Copy
.center_float_outer_container overflow: hidden .center_float_container position: relative left: 50% float: left .center_float position: relative left: -50% float: left .clear clear: both

Together with this helper:

Copy
# Rails 3 def center_float(&block) concat( content_tag(:div, :class => 'center_float_outer_container') do content_tag(:div, :class => 'center_float_container') do content_tag(:div, :class => 'center_float', &block) end end + content_tag(:div, :class => 'clear') ) end
Copy
# Rails 2 def center_float(&block) html = "".html_safe html << content_tag(:div, :class => 'center_float_outer_container') do content_tag(:div, :class => 'center_float_container') do content_tag(:div, h(capture(&block)), :class => 'center_float').html_safe end end html << content_tag(:div, :class => 'clear') html end

Use it with

Copy
<% center_float do %> This is centered. <% end %>

Works IE7 and up.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Tobias Kraze
Last edit:
about 5 years ago
by Besprechungs-PC
Keywords:
css
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more