Center a position:fixed element
Asked Answered
I

24

604

I would like to make a position: fixed; popup box centered to the screen with a dynamic width and height. I used margin: 5% auto; for this. Without position: fixed; it centers fine horizontally, but not vertically. After adding position: fixed;, it's even not centering horizontally.

Here's the complete set:

.jqbox_innerhtml {
    position: fixed;
    width: 500px;
    height: 200px;
    margin: 5% auto;
    padding: 10px;
    border: 5px solid #ccc;
    background-color: #fff;
}
<div class="jqbox_innerhtml">
    This should be inside a horizontally
    and vertically centered box.
</div>

How do I center this box in screen with CSS?

Insignificance answered 5/1, 2010 at 12:29 Comment(0)
D
804

If your div has a known width and height, then you basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.

position: fixed;
width: 500px;
height: 200px;
top: 50%;
left: 50%;
margin-top: -100px; /* Negative half of height. */
margin-left: -250px; /* Negative half of width. */

Or, if your div has a dynamic/undefined width and/or height, then instead of the margin, set the transform to the negative half of the div's relative width and height.

position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Or, if your div has at least a fixed width and you don't really care about centering vertically, then you can instead also add left: 0 and right: 0 to the element having a margin-left and margin-right of auto, so that the fixed positioned element having a fixed width knows where its left and right offsets start. In your case thus:

position: fixed;
width: 500px;
margin: 5% auto; /* Only centers horizontally not vertically! */
left: 0;
right: 0;
Drusilladrusus answered 5/1, 2010 at 12:39 Comment(11)
I found that trick in css-tricks.com/…. But when I change the width and height, it's not moving center. Ya, I should change the margin-left and top when change height and width.Insignificance
FYI: this will correctly position things in the middle, but unfortunately you lose your scroll-bars - any content clipped off by the viewport won't be reachable, even if you scroll, because the fixed position is based on the viewport, not the page. So far, the only solution I've found to that is with javascript.Messere
Groxx I think you could put scroll bars inside a div in the pop up using the overflow property.Mucoid
Besides, for this one you need to know the element's width.Reading
@Insignificance For some reason the margin-top and margin-left are not working for me. But the alternative in the post you linked (translate -50% -50%) worked perfectlyPottage
@David: as outlined in the article, that's only necessary if the element doesn't have a fixed width/height. However, in OP's case, the element has a fixed width/height, so the translate is unnecessary.Drusilladrusus
Nice combination of margin: x auto with left:0 right:0 ;) worked perfectly!Janeejaneen
Not sure why this get so many votes. It doesnt center correctly if the div is larger than 200px (height, but same for width)Luteous
BalusC: Arrogance. I read it ,yes: "set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div." -- so that makes it static width and height, right? Have you noticed the question specifically stated dynamic?Luteous
@nights: "dynamic" concerns the screen, not the element. So the element stays centered even when screen resizes. Have you read the question's code too? The element has a fixed width/height. Not sure why you're being so negative.Drusilladrusus
ah. nm if thats the case, i mean of course the browser size will be dynamic, not sure why that was in the question. instead i thought he meant that the popup dimensions needed to be dynamic. thats the case for me so im using transform: translate(-50%, -50%); works great except not on IE8.Luteous
S
513

I want to make a popup box centered to the screen with dynamic width and height.

Here is a modern approach for horizontally centering an element with a dynamic width - it works in all modern browsers; support can be seen here.

Updated Example

.jqbox_innerhtml {
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
}

For both vertical and horizontal centering you could use the following:

Updated Example

.jqbox_innerhtml {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

You may wish to add in more vendor prefixed properties too (see the examples).

Spin answered 14/9, 2014 at 2:25 Comment(8)
this messes up chrome. for very long divs, for whatever reason, it starts to aisle.Quiver
@dolphonebubleine Can you please provide an example?Spin
I'm using this approach to horizontally center a fixed positioned image which width is greater than window width and working fine atleast in current Firefox, Chrome, IE 11 and Edge versions.Delicacy
In my testing this works very well (behind prefixes), Win10 Edge 14, Win7 IE9+, Win10 Chrome, OSX Chrome, iPad4 Chrome & Safari, Android 4.4+ Chrome. Only failure for me was Android 4.0 where the translation did not occur.Markel
@ahnbizcad, this works in desktop browsers like Chrome 61, Safari 11 and FireFox 65, but not in Chrome 61 on Android 6, the accepted answer works in all browsers.Bohemianism
This makes images blurry in Chrome.Leflore
Somehow only approach that worked proper across all browser with my img. Thanks a bunch!Kaufman
This seemed to work really well at first, but... anyone with drag-and-drop elements on their pages beware: this method created problems with SortableJS for me. The elements being dragged would, as soon as they were grabbed, jump to their original positions before transform gets calculated. I am now using a variation on Will Prescot's answer instead, with no issues so far.Armanda
B
146

Or just add left: 0 and right: 0 to your original CSS, which makes it behave similarly to a regular non-fixed element and the usual auto-margin technique works:

.jqbox_innerhtml
{
  position: fixed;
  width:500px;
  height:200px;
  background-color:#FFF;
  padding:10px;
  border:5px solid #CCC;
  z-index:200;
  margin: 5% auto;
  left: 0;
  right: 0;
}

Note you need to use a valid (X)HTML DOCTYPE for it to behave correctly in IE (which you should of course have anyway..!)

Beira answered 5/1, 2010 at 12:53 Comment(9)
In what sense? The parent element is the body element, which has no borders. If you added border properties to the body (?!) then sure it would be affected, as would the 50% technique I imagine. I assure you it works just fine with the given parameters, just verified in every browser I have handy, and has the added benefit of not being dependent on the width of the element.Beira
All I did was add those 2 properties and a doctype to the OP's example HTML. However on further testing it seems that IE7 (or 8 in compat mode) is the problem - it seems it does not respect the value of the right property if left is also set! ( msdn.microsoft.com/en-us/library/… notes that left and right only have "partial" support in IE7). OK, I concede this solution is no good if IE7 support is important, but a great trick to remember for the future :)Beira
this should be the accepted answer. I had two fixed positions one for the opacity mask another for the modal. this was the only way I could center the fixed position modal in the center of the screen. Awesome answer who would have thought?Eaten
I agree, this should be the accepted answer. It works perfectly in responsive design, too, as it is not dependant on width.Reading
I would suggest to simplify the answer, as some of the css is relevant only for the OP. All you need is position: fixed; left: 0; right: 0; margin: 0 auto; .Reading
Can anyone explain why adding left and right makes margin:0 auto work?Date
@Date Because margin: auto centres horizontally a fixed/absolutely positioned element only if values of left, right and width on this element aren't auto.Command
Worked for me with a width:100%; and a max-width:1280px;Monochord
that only works if the width is set (or max width)Raccoon
A
35

Add a container like:

div {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
}

Then put your box into this div will do the work.

Edit: as mentioned in the comments, the inner content needs to be set to display: inline-block assuming there're two divs like:

    <div class="outer">
        <div class="inner">
             content goes here
        </div>
    </div>

Then the CSS for the inner needs to be:

    .outer {
        position: fixed;
        text-align: center;
        left: 0;
        right: 0;
    }
    .inner {
        display: inline-block;
    }

Together with the outer div having a left: 0; right:0; and text-align: center this will align the inner div centered, without explicitly specifying the width of the inner div.

Anguilla answered 14/7, 2012 at 12:47 Comment(4)
"text-align: center" didn't work for me in centering the internal div.Masefield
The internal box needs to be display: inline-block for this to work. (Some other display values might also work, such as table.)Hazardous
a better approach to the above mentioned css would be adding margin:auto; and changing width to width:50% or width:400px. then the contents can be straight text, block elements, or inline elements.Australopithecus
This solution has the added benefit of not blurring the textual content in MSIE and Chrome which occurs when "transform" is used.Fug
M
29

Center fixed position element
(the simple & best way I know)

position:fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));

For centering it horizontally & vertically (if height is same as width)

position:fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

Both of these approaches will not limit centered element's width less than viewport width, when using margins in flexbox, inside centered element

Meetinghouse answered 13/1, 2021 at 1:44 Comment(0)
P
27

Just add:

left: calc(-50vw + 50%);
right: calc(-50vw + 50%);
margin-left: auto;
margin-right: auto;
Progression answered 8/3, 2017 at 5:43 Comment(2)
This doesn't work with position: fixed, which is what the question is about. If I'm wrong, please edit your answer to include a runnable code snippet.Mongol
It works with position: fixed, provided set the max-width or width to the element.Collinsworth
E
11
#modal {
    display: flex;
    justify-content: space-around;
    align-items: center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}

inside it can be any element with diffenet width, height or without. all are centered.

Eyesight answered 1/5, 2019 at 14:2 Comment(0)
S
5
left: 0;
right: 0;

Was not working under IE7.

Changed to

left:auto;
right:auto;

Started working but in the rest browsers it stop working! So used this way for IE7 below

if ($.browser.msie && parseInt($.browser.version, 10) <= 7) {                                
  strAlertWrapper.css({position:'fixed', bottom:'0', height:'auto', left:'auto', right:'auto'});
}
Scrubby answered 22/12, 2011 at 10:29 Comment(2)
Do you mind editing your answer to include the entire solution?Mongol
This won't work without an auto margin on left and right sides.Slough
A
5

This solution does not require of you to define a width and height to your popup div.

http://jsfiddle.net/4Ly4B/33/

And instead of calculating the size of the popup, and minus half to the top, javascript is resizeing the popupContainer to fill out the whole screen...

(100% height, does not work when useing display:table-cell; (wich is required to center something vertically))...

Anyway it works :)

Aventurine answered 7/3, 2012 at 19:27 Comment(0)
H
4

I used vw (viewport width) and vh (viewport height). viewport is your entire screen. 100vw is your screens total width and 100vh is total height.

.class_name{
    width: 50vw;
    height: 50vh;
    border: 1px solid red;
    position: fixed;
    left: 25vw;top: 25vh;   
}
Heaves answered 4/4, 2019 at 21:20 Comment(0)
S
3

You can basically wrap it into another div and set its position to fixed.

.bg {
  position: fixed;
  width: 100%;
}

.jqbox_innerhtml {
  width: 500px;
  height: 200px;
  margin: 5% auto;
  padding: 10px;
  border: 5px solid #ccc;
  background-color: #fff;
}
<div class="bg">
  <div class="jqbox_innerhtml">
    This should be inside a horizontally and vertically centered box.
  </div>
</div>
Swenson answered 11/11, 2017 at 19:18 Comment(0)
J
2

I just use something like this:

.c-dialogbox {
    --width:  56rem;
    --height: 32rem;

    position: fixed;

    width:  var(--width);
    height: var(--height);
    left:   calc( ( 100% - var(--width) ) / 2 );
    right:  calc( ( 100% - var(--width) ) / 2 );
    top:    calc( ( 100% - var(--height) ) / 2 );
    bottom: calc( ( 100% - var(--height) ) / 2 );
}

It centers the dialog box both horizontally and vertically for me, and I can use different width and height to fit different screen resolutions to make it responsive, with media queries.

Not an option if you still need to provide support for browsers where CSS custom properties or calc() are not supported (check on caniuse.)

Jule answered 13/12, 2019 at 12:50 Comment(0)
W
2

This one worked the best for me:

    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
Whilst answered 8/5, 2020 at 19:54 Comment(0)
T
1

To fix the position use this :

div {
    position: fixed;
    left: 68%;
    transform: translateX(-8%);
}
Truncation answered 27/9, 2018 at 14:53 Comment(1)
Please provide an explanation on why your solution would work for the question posted.Skiver
F
1

simple, try this

position: fixed;
width: 500px;
height: 300px;
top: calc(50% - 150px);
left: calc(50% - 250px);
background-color: red;
Feigin answered 13/7, 2020 at 13:54 Comment(0)
W
1

You could set something like this

.modal {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;

}
Wrongheaded answered 29/4, 2023 at 20:4 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Intercessory
N
0

One possible answer:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>CSS Center Background Demo</title>
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }

        div.centred_background_stage_1 {
            position: fixed;
            z-index:(-1 );
            top: 45%;
            left: 50%;
        }

        div.centred_background_stage_2 {
            position: relative;
            left: -50%;

            top: -208px;
            /* % does not work.
               According to the
               http://reeddesign.co.uk/test/points-pixels.html
               6pt is about 8px

               In the case of this demo the background
               text consists of three lines with
               font size 80pt.

               3 lines (with space between the lines)
               times 80pt is about
               ~3*(1.3)*80pt*(8px/6pt)~ 416px

               50% from the 416px = 208px
             */

            text-align: left;
            vertical-align: top;
        }

        #bells_and_wistles_for_the_demo {
            font-family: monospace;
            font-size: 80pt;
            font-weight: bold;
            color: #E0E0E0;
        }

        div.centred_background_foreground {
            z-index: 1;
            position: relative;
        }
    </style>
</head>
<body>
<div class="centred_background_stage_1">
    <div class="centred_background_stage_2">
        <div id="bells_and_wistles_for_the_demo">
            World<br/>
            Wide<br/>
            Web
        </div>
    </div>
</div>
<div class="centred_background_foreground">
    This is a demo for <br/>
    <a href="https://mcmap.net/q/55272/-center-a-position-fixed-element">
        https://mcmap.net/q/55272/-center-a-position-fixed-element
    </a>
    <br/><br/>
    <a href="http://www.starwreck.com/" style="border: 0px;">
        <img src="./star_wreck_in_the_perkinnintg.jpg"
             style="opacity:0.1;"/>
    </a>
    <br/>
</div>
</body>
</html>
Nondescript answered 5/8, 2013 at 3:11 Comment(1)
This does seem to work, although it requires you to already know the width and height of the element.Mongol
F
0

Try using this for horizontal elements that won't center correctly.

width: calc (width: 100% - width whatever else is off centering it)

For example if your side navigation bar is 200px:

width: calc(100% - 200px);
Fabe answered 7/1, 2017 at 16:58 Comment(0)
S
0

This works wonderfully when you don't know the size of the thing you are centering, and you want it centered in all screen sizes:

.modal {
  position: fixed;
  width: 90%;
  height: 90%;
  top: 5%;           /* (100 - height) / 2 */
  left: 5%;          /* (100 - width) / 2 */
}
St answered 26/7, 2020 at 23:43 Comment(0)
C
0

What I use is simple. For example I have a nav bar that is position : fixed so I adjust it to leave a small space to the edges like this.

nav {
right: 1%;
width: 98%;
position: fixed;
margin: auto;
padding: 0;
}

The idea is to take the remainder percentage of the width "in this case 2%" and use the half of it.

Cocoa answered 28/1, 2021 at 18:47 Comment(0)
S
0

Had this problem so I concluded that using a (invisible) container is the best option (based on answer @Romulus Urakagi Ts'ai). To make it with flexbox:

.zoom-alert {
  position: fixed;
  justify-content: center;
  display: flex;
  bottom: 24px;
  right: 0;
  left: 0;
  z-index: 100000;
  width: 100%;

  &__alert {
    flex: 0 0 500px;
    padding: 24px;
    background-color: rgba(212, 193, 105, 0.9);
    border: 1px solid rgb(80, 87, 23);
    border-radius: 10px;
  }
}

(the syntax is SCSS but can be easily modified to pure CSS)

fixed centered alert

Sulphonamide answered 23/10, 2021 at 9:38 Comment(0)
I
0

Center element of a div with the property of

position:fixed

Html and Css code

.jqbox_innerhtml {
   position: fixed;
   width:100%;
   height:100%;
    display: flex;
    justify-content: space-around;
    align-items: center;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border: 5px solid #ccc;
    background-color: #fff;
}
<div class="jqbox_innerhtml">
    This should be inside a horizontally
    and vertically centered box.
</div>
Instrumentalist answered 2/6, 2022 at 20:32 Comment(0)
A
-2

Another simple solution is to set the width of the element to fit-content and set the left and right to 0px;

width: fit-content;
position: fixed;
left: 0px;
right: 0px;

This is useful if you don't know the width of the element.

Adhesion answered 9/7, 2022 at 21:31 Comment(0)
G
-15

The only foolproof solution is to use table align=center as in:

<table align=center><tr><td>
<div>
...
</div>
</td></tr></table>

I cannot believe people all over the world wasting these copious amount to silly time to solve such a fundamental problem as centering a div. css solution does not work for all browsers, jquery solution is a software computational solution and is not an option for other reasons.

I have wasted too much time repeatedly to avoid using table, but experience tell me to stop fighting it. Use table for centering div. Works all the time in all browsers! Never worry any more.

Gaekwar answered 10/5, 2013 at 14:53 Comment(1)
This doesn't answer the question at all. There's no non-CSS equivalent to position:fixed.Hazardous

© 2022 - 2024 — McMap. All rights reserved.