The first step is to add CSS
position: fixed;to the target element with its
topand
leftattributes both equal to
50%.
The target element now appears like this:
There is a problem -- setting left and top to 50% does not make it centered. Instead, the element shifted a bit from the center. To solve this, finish step 2 below.
The next step is to adjust the extra pixels shifted from the center. We can set its
margin-leftand
margin-topto -1*(its width) and -1*(its height) respectively. For instance, a
divwith width:400px should set
margin-left: -200px. With this approach, the element shifts back to center and keeps centered all the time.
Note: The element width and height should be a fixed value.
The following code summarizes the demo:
Here is a Live Demo of this example.
Update 7 Nov 2015: Updated source code section to GitHub version