CSS

Guil Hernandez
STAFF
Guil Hernandez
Treehouse Teacher

Forum Tip: Centering Floated Elements

Hi everyone,

Ever tried center aligning an element containing floats? It can be tricky, which often leaves us fiddling around with margins and width values to get it perfectly centered. So I created a forum tip that covers why this happens and the best way to get perfect center alignment.

Mostly because it's displayed inline-block and the text-align: center... centers it...

Andrew Lawrence
Andrew Lawrence
Pro Student 3,824 Points

Guil,

Thank you so much for this video. A big thank you as well, to a lot of people who commented on this video.

HTML and CSS have really been my ‘gateway drug’ into coding, and thanks to Treehouse I’m really falling in love the process. I’ve been struggling with CSS layout techniques, however. I feel like there are several perhaps more ‘advanced’ logical/creative challenges I have overcome in CSS and beyond, but for some reason I always find myself at a loss when it comes back to making my elements fit into the design I have in my head. It is the most time consuming and honestly the most frustrating aspect of web design for me because I feel like I should be able to do it, firstly, and secondly because I feel like my expectations of browser behavior never match what it actually does!

Reading other peoples frustrations, and seeing Guil talk us through this surprisingly complex topic was immensely helpful. Thank you, so very much.

David Wickes
David Wickes
2,423 Points

Domo arigato, Mr. Hernandez!

Great tip, thank you very much!! I wish this had been posted two months ago when I first came across the issue (took me three weeks to figure it out myself lol). Well at least now I know WHY it works, thanks Guil!

Osman Safa Kaya
Osman Safa Kaya
556 Points

I was looking for this solution for a while, thank you very much!

Dwayne Neckles
Dwayne Neckles
1,715 Points

This is super helpful, thanks!!!

Ryan Frizzell
Ryan Frizzell
14,354 Points

Wow, I ran into this exact problem on a project this year, and went with the fixed width option... now I regret that decision.

Thank You very much very helpful and informative.

Shadab Khan
Shadab Khan
5,214 Points

Hi Guil, I am not getting this concept. What else can I try to understand this better?

32 Answers

this is awesome... thanks a ton... I've been wondering about this for ages.

Natasha McDiarmid
Natasha McDiarmid
11,389 Points

Great tip. I always fiddle with the margin values, which to your point, isn't future proof.

Thanks guill, great tip, I have a suggestion for a future forum tip, I'd like to know how can i center an element not only horizontally but vertically, with percentanges for a fluid responsive page, for example if i want an image always in the center of the screen not only horizontally but vertically, this for a "welcome" web page were the user always see the image centered in the middle despite the device used

This is a late response, but for anyone else that see's...

For absolute centering percentage widths, I would say use absolute positioning top: 50%, and left: 50%, then bring it back with a transform: translate (-50%, -50%);

Perfect centering :)

CodePen Example

thank you!

Christopher Zenner
Christopher Zenner
9,566 Points

Hi, Guil!

Thanks for the great tip. I'm battling this one myself on a small, personal project. Unfortunately, this didn't work for me, and I'm wondering why. Unlike your example, I have a .wrapper div that contains several other smaller divs which mimic Post-it® notes. The .wrapper div sits inside another div identified as #bulletin-board. I defined the property display: inline-block; in my .wrapper selector, but it's still expanding to fill the full width of the #bulletin-board, and none of my .post-its are centered. Is this because each of the .post-its (i.e., the elements contained within .wrapper) are also divs, rather than inline elements?

For your reference, I'm including a few code snippets below:

#bulletin-board {
    background: #eee url('../img/cork.png') repeat;
    border: 15px ridge dimgray;
    border-radius: 10px;
    margin: 20px auto;
    overflow: auto;
    width: 90%;
}

.wrapper {
    display: inline-block;
    overflow: hidden;
    text-align: center;
}

.post-it {
    float: left;
    font: normal 1.25em 'Covered By Your Grace', cursive;
    line-height: 1.15em;
    text-align: left;
    margin: 1em;
    width: 16.5em;
    height: 16.5em;
}
Christopher Zenner
Christopher Zenner
9,566 Points

Hi again, Guil.

I have to recant what I said earlier; the fix in your video does work for me as long as my notes remain on a single line. The minute the browser contracts enough to push one of them down to the next line, my inline-block .wrapper expands to fill the entire #bulletin-board. I set up a test project in my workspaces so you could see the behavior I'm describing: http://teamtreehouse.com/workspaces/67472#.

There's probably a very simple explanation and/or fix for this, but it's eluding me at the moment. Any help would be appreciated. (I'm currently in your CSS Layout Techniques section so perhaps I'll discover the answer.)

Thanks so much, and I'm very sorry for the misinformation earlier! =/

Thanks Guil!!

Guil Hernandez , Great tip, a question ... how to create and use with nesting navigation?

Calvin Maighan
Calvin Maighan
12,061 Points

Absolutely loving the tips keep em coming! The playlist was great too, a great place to refer back to as well once I start building websites of my own from scratch (very soon yay!).

thanks guil, nice tip

Axel Will
Axel Will
4,022 Points

Would be nice to make a Note and Pin the Video to my Profile to find it again when needed later. Or Click a heart or Favorites-Icon. To collect vids with personal notes and make your own Collection.

Thank you Guil for sharing your Great knowledge

Thank you!! Awesome tip!! ;)

Jimmy Xander
Jimmy Xander
7,978 Points

With the "display inline-block, if you remove the whitespace between the elements in the code. In this case the <li> tags. The space between them will dissapear, no need to use a negative margin.

Guil Hernandez
Guil Hernandez
Treehouse Teacher

Jimmy Xander – Right, but I'd rather not affect the presentation via the HTML. I cover that at around the 8:45 mark of this video.

Ashley Dillon
Ashley Dillon
9,092 Points

THANK YOU!! Couldn't figure this out for age!

That was a great video and had a lot of useful tips for people needing to format their pages, but I don't really like the negative margin solution you gave us for the problem of gaps between elements. I understand wanting to keep presentation and content confined to CSS and HTML respectively, but the problem with the gaps between inline elements isn't with the presentation. The problem is with the content.

What happens if in the future, the rules change so tabs and new lines don't cause extra 'Space' characters to be added between elements? Every page with a negative pixel margin to account for extra 'Space' characters will need to be changed.

Even without taking into account future changes to the internet, adding negative pixels margins can cause problems for users right now. The first choice of font doesn't always get loaded; if the fallback font options require a different negative margin, the page might not render properly. Also, if users have personal styles set up to make fonts larger or smaller, the negative margin probably won't have the right value.

I dislike the solution of not having white space between the elements in the code because it makes the code hard to maintain. Instead, I think the best way to handle the problem with the unwanted content is to use HTML comments to remove it.

  <ul><!--
    --><li><a href="#">Home</a></li><!--
    --><li><a href="#">About</a></li><!--
    --><li><a href="#">Work</a></li><!--
    --><li><a href="#">Contact</a></li> 
  </ul>

This way of solving the problem has several benefits over both the negative margin and the white space removal solutions:

  1. The page will render correctly regardless of font sizes or user style sheets.
  2. The page will render correctly regardless of changes in the way HTML is handled by browsers in the future.
  3. Organization of the code is kept intact for ease of maintenance.

Code Pen Demo of Comment Solution

I've just been through both CSS deep dives and am putting everything into practice now. This is something I've been struggling with, so awesome tip (and great timing for me, too).

awesome tip! thanks Guil! :D

How to set up the following code from codepen, to actually make it work with coda. So far Im getting just a red page with white text on, when I copy and paste this two code forms. Any help would be appreciated.

This one goes to html: '''<header> <h1>My Site!</h1> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Work</a></li> <li><a href="#">Contact</a></li> </ul> </header> <div> <p>Tattooed viral put a bird on it skateboard. Drinking vinegar locavore squid farm-to-table, dreamcatcher tattooed kitsch scenester. Tousled wolf squid Wes Anderson PBR, Williamsburg banh mi dreamcatcher stumptown ethnic sartorial mlkshk. Hella mixtape bespoke mustache Bushwick. Post-ironic hashtag jean shorts, Truffaut organic roof party pop-up wayfarers selvage narwhal. Williamsburg kale chips beard, artisan XOXO occupy pickled. Mixtape roof party twee, post-ironic bespoke hella artisan meggings Carles brunch pop-up Tonx street art normcore. DIY paleo slow-carb occupy tofu fingerstache. Wayfarers butcher trust fund wolf, fap messenger bag quinoa flannel sartorial organic.</p> </div> '''

And this one to CSS:

'''body { padding: .5% 14%; } header { margin-bottom: 44px; text-align: center; } ul { padding: 0; margin: 0; list-style-type: none; overflow: hidden; display: inline-block; background: tomato; } li { float: left; padding: 10px 22px; background: steelblue; border-left: 1px solid #3b6c94; } '''

Nice pattern Guil. But one thing i don't get, why the p tag is displayed in a 2 column layout. There is no property targeting neither the div nor the p tag. how could that actually be displayed that way at all?!? Ok if i go to the dev tool s i see what is leading to that column layout ( webkit-column-count and webkit-column-gap). but they aren't defined anywhere inside your pen. That's odd. Best regards Ralf

Click the gear icon at the top left of the HTML entry area. The code for the columns is in the "Stuff for <head>" section.

<style>
body {
  font: 1em/1.5 sans-serif;
  color: white;
  background: #ff7f69 ;
}
a {
  text-decoration: none;
  color: white;
  text-transform: uppercase;
}
h1 {
  margin-bottom: 30px;
  text-shadow: 0 2px 0 rgba(0,0,0, .2);
}
ul li:first-child {
  border: none;
}
div {
  clear: both;
  column-count: 2;
  column-gap: 20px;
}
p {
  margin-top: 0;
}
</style>

Ahhhhhhhh cool! Haven't noticed that yet. Good to know. Thank you

Rafael Ferreira
Rafael Ferreira
13,086 Points

Awesome tip. Thanks a lot Guil!

Very well presented. Great work. Although I already practice this technique, it was definitely a video worth watching!

Thank you, I had resorted to messing with the width values this saved me.

Wonderful explanation, thank you Guil!

Can you do the same with Flexbox?

Veronica Rivera
Veronica Rivera
32,464 Points

Thanks for this. It really helped me not only with text navigation but also with images. I had an image gallery and I put them in an ul and then put the display: inline-block: in the ul and it centered it like a charm and it stayed centered throughout all of my responsive layout without having to write any additional styles for it in my media queries. So even when they collapsed in the tablet and phone views they stayed centered so it all worked out.

Benny Chew
PRO
Benny Chew
Pro Student 2,717 Points

Thanks a lot for this tip, very helpful. This has bugged me for many times. Now I must remember to set inline-block for the parent element.

thanks:)