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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)