Read more

Center a float horizontally

Tobias Kraze
May 26, 2011Software engineer at makandra GmbH

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.


Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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:

.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:

# 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
# 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

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

Works IE7 and up.

Posted by Tobias Kraze to makandra dev (2011-05-26 20:28)