Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGuil Hernandez
Treehouse TeacherForum 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.
Andrew Lawrence
Courses Plus Student 3,824 PointsGuil,
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
2,423 PointsDomo arigato, Mr. Hernandez!
Travis Torres
2,949 PointsGreat 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
556 PointsI was looking for this solution for a while, thank you very much!
Dwayne Neckles
1,715 PointsThis is super helpful, thanks!!!
Ryan Frizzell
14,527 PointsWow, I ran into this exact problem on a project this year, and went with the fixed width option... now I regret that decision.
Yosef Juarez
9,313 PointsThank You very much very helpful and informative.
Shadab Khan
5,470 PointsHi Guil, I am not getting this concept. What else can I try to understand this better?
Domonic Webster
Front End Web Development Techdegree Student 1,909 PointsThanks for going through the options.
32 Answers
Natasha McDiarmid
11,400 PointsGreat tip. I always fiddle with the margin values, which to your point, isn't future proof.
Wendell Pulsipher
10,183 Pointsthis is awesome... thanks a ton... I've been wondering about this for ages.
juan reyna
4,907 PointsThanks 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
Guil Hernandez
Treehouse Teacherjuan reyna Maybe this video will help ya out. :)
alextadevosyan
5,889 PointsThis 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 :)
Axel Will
4,022 PointsWould 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
James Baxter
414 PointsVery well presented. Great work. Although I already practice this technique, it was definitely a video worth watching!
Sylinic .
2,761 PointsWonderful explanation, thank you Guil!
Christian Erlebach
Full Stack JavaScript Techdegree Graduate 49,431 PointsThanks for this great tip ...
juan reyna
4,907 Pointsthank you!
Christopher Zenner
9,566 PointsHi, 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
9,566 PointsHi 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! =/
Zinamarie Zeno
Front End Web Development Techdegree Student 8,590 PointsThank you! This helped tremendously! :)
COURTNEY HALL
7,505 PointsThanks Guil!!
Gonzalo Guevara
14,380 PointsGuil Hernandez , Great tip, a question ... how to create and use with nesting navigation?
Calvin Maighan
12,061 PointsAbsolutely 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!).
Tom Parandyk
3,241 PointsYup! Nice one.
hassanboulhilt
5,775 Pointsthanks guil, nice tip
Christoph Hawlik
11,867 PointsThank you! :)
Diogo Vaz
3,284 PointsThank you!! Awesome tip!! ;)
Jimmy Xander
7,978 PointsWith 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
Treehouse TeacherJimmy 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
9,092 PointsTHANK YOU!! Couldn't figure this out for age!
Adrian Melendez
5,555 PointsThat 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:
- The page will render correctly regardless of font sizes or user style sheets.
- The page will render correctly regardless of changes in the way HTML is handled by browsers in the future.
- Organization of the code is kept intact for ease of maintenance.
Eric Bateman
23,928 PointsI'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).
joeboo2529
9,805 Pointsawesome tip! thanks Guil! :D
Nijat Mcmudow
1,755 PointsHow 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; } '''
Ralf Koller
4,506 PointsNice 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
Adrian Melendez
5,555 PointsClick 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>
Ralf Koller
4,506 PointsAhhhhhhhh cool! Haven't noticed that yet. Good to know. Thank you
Rafael Ferreira
13,086 PointsAwesome tip. Thanks a lot Guil!
Matthew Welch
7,370 PointsThank you, I had resorted to messing with the width values this saved me.
Ernst van Megen
3,541 PointsCan you do the same with Flexbox?
Veronica Rivera
32,599 PointsThanks 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
Courses Plus Student 2,717 PointsThanks 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.
Peter Vanderlind de Oliveira
7,376 PointsGreat :D
Please do more vids about the topic.
Ben Basty
23,772 Pointsthanks:)
Daniel Ramirez
Courses Plus Student 684 PointsDaniel Ramirez
Courses Plus Student 684 PointsMostly because it's displayed inline-block and the text-align: center... centers it...