← back to the blog


How to center fixed elements with JavaScript and jQuery

Posted on November 20th, 2018 in JavaScript by George

 

Sometime using top, right, bottom and left on a fixed element is not enough. 

I am sure you have been in the situation when you want to center a div container, image or other any html element which is position fixed. In this article you will find out how to center any block element in the center of the screen using JavaScript and jQuery.

This is going to be achived using jQuery but can be done with plain JavaScript as well.

 

Center Horizontal position fixed element.

 

We will create a jQuery helper function! This function is going to be available in the jQuery object to be able to use it more than one time.

The code bellow is wrapping the element in the jQuery object and then is calling centerFixedElementHorizontal method.

The centerFixedElementHorizontal method first is going to apply the css property of fixed on the element and then is going to apply the left property .

Left property value is calculated using the window width where you want to subtract half of the outerwidth value of the element and add the window scroll left value.

 

  jQuery.fn.centerFixedElementHorizontal = function() {
   
    this.css('position', "fixed");
     this.css("left", Math.max(0, ((jQuery(window).width() 
                                  - jQuery(this).outerWidth()) / 2) 
                                  + $(window).scrollLeft()) + "px");
    
   return this;

  }

//type takes a string "fixed" or "absolute" to define the position property

// now use like this

jQuery(element).centerFixedElementHorizontal();

 

Here is codepen example CODEPEN LINK