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 trial

CSS CSS Basics (2014) Basic Layout Floats

Float Vs. Flex. Can't center 3 floated items.

Hello Treehouse community, I need help regarding one topic.

I am playing around trying to center 3 floated elements. Although I can probably do it with 2 single elements, I am unable to do add space in between when I float 3 elements.

Let's get to the point. This is how I center 3 elements using the flex technique. For your convenience, I created a Code Pen:

https://codepen.io/DeMichieli/pen/ywRKzN

This is the same structure, trying to float 3 centered elements with space in between:

https://codepen.io/DeMichieli/pen/qvJYaM

When I add some margin, left or right, to the ".box" element, the structure breaks. Even if I add 1px boarder as well.

If I substitute the "width" from a percentage value to a pixel value, the boxes get stacked together to the left.

.box {
 width: 200px;
 float: left;
 }

Any ideas on how to center those elements with space in between? What are the benefits of a technique versus the other?

Thanks for your support.

Kind regards, Alex

1 Answer

Steven Parker
Steven Parker
229,732 Points

You can add borders to your column boxes, but you must use a different sizing model to prevent overflowing the total width:

.box {
  width: 33.33%;
  float: left;
  box-sizing: border-box;    /* make borders count as part of the width */
  border: 20px solid white;
}

Unfortunately, there is no "margin-box" sizing model, so if you want to add margins you must compensate for them by reducing the percentage width.

I think you have already demonstrated how flexbox is a far superior technique to floats for creating column layouts.

Hello Steven,

Thanks for your response!

I completely forgot about the "border box" property, thanks for that! I managed to "center" (it looks totally wonky) the 3 columns, here's an update: https://codepen.io/DeMichieli/pen/qvJYaM?editors=1100#0

I had to break the code for 3 different boxes instead of having one selector for all of them.

Thanks, Alex

Steven Parker
Steven Parker
229,732 Points

So "border-box" doesn't help for the margins, but the "calc" function could be used to accurately compensate for them:

.box1 {
  width: calc(33.33% - 20px);
  margin: 0 10px;
}

Happy coding!