Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

centering a div between one that's floated right and one that's floated left

Tags:

html

css

center

I have a page in which a header consists of three divs - one that's floated to the left, one that's floated to the right, and one that's in between them. I'd like for that central div to be centered, yet sadly float: center doesn't exist and I can't just float it to the left and add padding as it'd have to change depending on the window size.

Is there something simple I'm overlooking? Or how would I do such a thing?

Update:
In addition, I'd like to find a way of centering that middle div in the space between the divs in case that looks better.

like image 361
Mala Avatar asked Jul 03 '10 20:07

Mala


People also ask

How do I center two divs floating?

Simply put, if you have a div, and the elements inside are set to “display:inline-block” then you can just use “text-align:center” to center them inside.

How do you center a floated element in CSS?

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.

How do I center within a div?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.


1 Answers

If you have two floated divs, then you know the margins. The problem is that the float:right div should be put before the middle div. So basically you will have:

left-floated | right-floated | centered

Now, about the margins: usually you can just use margin:0 auto, right? The problem is that right now you know the values of the margins: floated divs! So you just need to use:

margin:0 right-floated-width 0 left-floated-width

That should work.

Years later edit

Meanwhile, a new toy is in town: flexbox. The support is fairly good (i.e. if you don't need to support lower than IE 10) and the ease of use is way over floats.

You can see a very good flexbox guide here. The example you need is right here.

like image 156
Ionuț Staicu Avatar answered Sep 19 '22 02:09

Ionuț Staicu