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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)