Center a float horizontally

Updated . Posted . Visible to the public.

This card shows you how to center a float horizontally in CSS. Also: find out what techniques are available for your use case and browser requirements in the card linked below.

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:

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

Tobias Kraze
Last edit
Rebecca
Keywords
css
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2011-05-26 18:28)