How do I center floated elements?
Asked Answered
H

12

399

I'm implementing pagination, and it needs to be centered. The problem is that the links need to be displayed as block, so they need to be floated. But then, text-align: center; doesn't work on them. I could achieve it by giving the wrapper div padding of left, but every page will have a different number of pages, so that wouldn't work. Here's my code:

.pagination {
  text-align: center;
}
.pagination a {
  display: block;
  width: 30px;
  height: 30px;
  float: left;
  margin-left: 3px;
  background: url(/images/structure/pagination-button.png);
}
.pagination a.last {
  width: 90px;
  background: url(/images/structure/pagination-button-last.png);
}
.pagination a.first {
  width: 60px;
  background: url(/images/structure/pagination-button-first.png);
}
<div class='pagination'>
  <a class='first' href='#'>First</a>
  <a href='#'>1</a>
  <a href='#'>2</a>
  <a href='#'>3</a>
  <a class='last' href='#'>Last</a>
</div>
<!-- end: .pagination -->

To get the idea, what I want:

alt text

Horvath answered 22/1, 2011 at 13:10 Comment(5)
The whole purpose of the float property is to position an element along the left or right side of its container.Shithead
@Rob: Well, I needed to define width and height for the link elements, which can be only done on block elements, but when you make the links block, they spread on new line each, that's why I made them floated.Horvath
Alternative solution, when you don't want to / can't use inline-block. #1232596Queue
I believe this question deserves moderator's attention as its current title and answers are misleading. The question is not about floating content in the center, but about centering content. Floating means the non-floating sibling content should fill the remaining gaps and that's clearly neither desired nor achieved here.Ventura
@AndreiGheorghiu if you think that, suggest an edit instead of flagging it for mods. Anyone can edit these questions, so edit the question and write a detailed explanation in the edit reason. This is something any user can do, it doesn't have to be a moderator. There's nothing wrong with the question or any answers that requires moderator interventionBreaker
E
454

Removing floats, and using inline-block may fix your problems:

 .pagination a {
-    display: block;
+    display: inline-block;
     width: 30px;
     height: 30px;
-    float: left;
     margin-left: 3px;
     background: url(/images/structure/pagination-button.png);
 }

(remove the lines starting with - and add the lines starting with +.)

.pagination {
  text-align: center;
}
.pagination a {
  + display: inline-block;
  width: 30px;
  height: 30px;
  margin-left: 3px;
  background: url(/images/structure/pagination-button.png);
}
.pagination a.last {
  width: 90px;
  background: url(/images/structure/pagination-button-last.png);
}
.pagination a.first {
  width: 60px;
  background: url(/images/structure/pagination-button-first.png);
}
<div class='pagination'>
  <a class='first' href='#'>First</a>
  <a href='#'>1</a>
  <a href='#'>2</a>
  <a href='#'>3</a>
  <a class='last' href='#'>Last</a>
</div>
<!-- end: .pagination -->

inline-block works cross-browser, even on IE6 as long as the element is originally an inline element.

Quote from quirksmode:

An inline block is placed inline (ie. on the same line as adjacent content), but it behaves as a block.

this often can effectively replace floats:

The real use of this value is when you want to give an inline element a width. In some circumstances some browsers don't allow a width on a real inline element, but if you switch to display: inline-block you are allowed to set a width.” ( http://www.quirksmode.org/css/display.html#inlineblock ).

From the W3C spec:

[inline-block] causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.

Evulsion answered 22/1, 2011 at 13:15 Comment(6)
Tip: Don't forget about vertical-align.Filiform
Yes, this is one of the few cases I've found where vertical-align actually does what you expect it to.Atavistic
The downside of this method is that it is hard to control the horizontal spacing, as whitespace may appear between elements.Rambunctious
@XavierPoinas: use font-size: 0; on the parent to fix that problemDiscomfiture
Keep in mind though that "font-size: 0" used not to work on Android devices. Not sure if this is still true for recent versions.Grappling
Also on MS Edge you have list style type dots, even if you set it to none.Mims
K
161

Since many years I use an old trick I learned in some blog, I'm sorry i don't remember the name to give him credits.

Anyway to center floating elements this should work:

You need a structure like this:

    .main-container {
      float: left;
      position: relative;
      left: 50%;
    }
    .fixer-container {
      float: left;
      position: relative;
      left: -50%;
    }
<div class="main-container">
  <div class="fixer-container">
    <ul class="list-of-floating-elements">

      <li class="floated">Floated element</li>
      <li class="floated">Floated element</li>
      <li class="floated">Floated element</li>

    </ul>
  </div>
</div>

the trick is giving float left to make the containers change the width depending on the content. Than is a matter of position:relative and left 50% and -50% on the two containers.

The good thing is that this is cross browser and should work from IE7+.

Kelly answered 2/2, 2014 at 8:22 Comment(8)
A reminder that this works if there is only 1 single float element.Impromptu
The problem with this is a horizontal scroll bar will appear because the outer div extends past the screen. Also when the list wraps to another line then the whole thing goes to left align.Liter
This won't make difference without setting the container max-width, margin: 0 auto; does a better a job in this caseHipbone
For me, float: left; was not necessary on .main-container and .fixer-container.Apices
@Liter I solved the horizontal scroll by wrapping everything in a single div with overflow: hidden;Apices
The purpose of floating an element is to have the rest of document content fill the space around that element which doesn't seem to be happening in this case, so it's not exactly floating, is it?Ventura
If the float breaks due to window size the "float" is not there anymore!Nardi
That might have been me: webmonkeyswithlaserbeams.wordpress.com/2008/07/09/float-center. I was searching for my old blog, and this SO question came up first.Diaz
D
40

Centering floats is easy. Just use the style for container:

.pagination{ display: table; margin: 0 auto; }

change the margin for floating elements:

.pagination a{ margin: 0 2px; }

or

.pagination a{ margin-left: 3px; }
.pagination a.first{ margin-left: 0; } 

and leave the rest as it is.

It's the best solution for me to display things like menus or pagination.

Strengths:

  • cross-browser for any elements (blocks, list-items etc.)

  • simplicity

Weaknesses:

  • it works only when all floating elements are in one line (which is usually ok for menus but not for galleries).

@arnaud576875 Using inline-block elements will work great (cross-browser) in this case as pagination contains just anchors (inline), no list-items or divs:

Strengths:

  • works for multiline items.

Weknesses:

  • gaps between inline-block elements - it works the same way as a space between words. It may cause some troubles calculating the width of the container and styling margins. Gaps width isn't constant but it's browser specific (4-5px). To get rid of this gaps I would add to arnaud576875 code (not fully tested):

    .pagination{ word-spacing: -1em; }

    .pagination a{ word-spacing: .1em; }

  • it won't work in IE6/7 on block and list-items elements

Disprize answered 5/6, 2013 at 21:32 Comment(3)
display: table trick is unbelievable just did everything as should with just only a few lines. I need to remember that. CheersSecor
The inline-block technique works extremely well. Luckily, the elements I'm using (nested div elements) this for can deal with the gap well.Lying
You can also remove the inline-block gaps by dropping the font size to zero, then restoring to your previous value inside the child elementsBroadloom
C
18

Set your container's width in px and add:

margin: 0 auto;

Reference.

Cystoscope answered 19/9, 2013 at 17:15 Comment(2)
for me, this is the best answer :P.Benson
This would only work if the container width is appropriate, which is the problem when it contains floated elements.Impromptu
S
14

Using Flex

.pagination {
  text-align: center;
  display:flex;
  justify-content:center;
}
.pagination a {
  display: block;
  width: 30px;
  height: 30px;
  float: left;
  margin-left: 3px;
  background: url(/images/structure/pagination-button.png);
}
.pagination a.last {
  width: 90px;
  background: url(/images/structure/pagination-button-last.png);
}
.pagination a.first {
  width: 60px;
  background: url(/images/structure/pagination-button-first.png);
}
<div class='pagination'>
  <a class='first' href='#'>First</a>
  <a href='#'>1</a>
  <a href='#'>2</a>
  <a href='#'>3</a>
  <a class='last' href='#'>Last</a>
</div>
<!-- end: .pagination -->
Sudiesudnor answered 25/1, 2017 at 7:28 Comment(0)
C
5
text-align: center;
float: none;
Castrato answered 22/2, 2015 at 10:34 Comment(0)
F
5

I think the best way is using margin instead of display.

I.e.:

.pagination a {
    margin-left: auto;
    margin-right: auto;
    width: 30px;
    height: 30px;    
    background: url(/images/structure/pagination-button.png);
}

Check the result and the code:

http://cssdeck.com/labs/d9d6ydif

Finis answered 28/5, 2015 at 6:49 Comment(1)
Works with just margin: auto; instead of the individial left & right properties too.Miscalculate
L
3

You can also do this by changing .pagination by replacing "text-align: center" with two to three lines of css for left, transform and, depending on circumstances, position.

.pagination {
  left: 50%; /* left-align your element to center */
  transform: translateX(-50%); /* offset left by half the width of your element */
  position: absolute; /* use or dont' use depending on element parent */
}
.pagination a {
  display: block;
  width: 30px;
  height: 30px;
  float: left;
  margin-left: 3px;
  background: url(/images/structure/pagination-button.png);
}
.pagination a.last {
  width: 90px;
  background: url(/images/structure/pagination-button-last.png);
}
.pagination a.first {
  width: 60px;
  background: url(/images/structure/pagination-button-first.png);
}
<div class='pagination'>
  <a class='first' href='#'>First</a>
  <a href='#'>1</a>
  <a href='#'>2</a>
  <a href='#'>3</a>
  <a class='last' href='#'>Last</a>
</div>
<!-- end: .pagination -->
Laporte answered 22/3, 2019 at 15:24 Comment(0)
S
2

IE7 doesn't know inline-block. You must add:

display:inline;
zoom: 1;
Swordplay answered 8/10, 2013 at 8:51 Comment(0)
B
1

Add this to you styling

position:relative;
float: left;
left: calc(50% - *half your container length here);

*If your container width is 50px put 25px, if it is 10em put 5em.

Birthright answered 23/5, 2017 at 21:0 Comment(0)
L
0
<!DOCTYPE html>
<html>
<head>
    <title>float object center</title>
    <style type="text/css">
#warp{
    width:500px;
    margin:auto;
}
.ser{
width: 200px;
background-color: #ffffff;
display: block;
float: left;
margin-right: 50px;
}
.inim{
    width: 120px;
    margin-left: 40px;
}

    </style>
</head>
<body>



<div id="warp">
            <div class="ser">
              <img class="inim" src="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">

              </div>
           <div class="ser">
             <img class="inim" sr`enter code here`c="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">

             </div>
        </div>

</body>
</html>

step 1

create two or more div's you want and give them a definite width like 100px for each then float it left or right

step 2

then warp these two div's in another div and give it the width of 200px. to this div apply margin auto. boom it works pretty well. check the above example.

Lonee answered 6/4, 2018 at 13:58 Comment(0)
D
-2

Just adding

left:15%; 

into my css menu of

#menu li {
float: left;
position:relative;
left: 15%;
list-style:none;
}

did the centering trick too

Devondevona answered 5/8, 2014 at 18:15 Comment(1)
15% is plain arbitrary.Impromptu

© 2022 - 2024 — McMap. All rights reserved.