Centering an Element Vertically

Centering an element vertically requires calculating the top margin based on the parent’s height and the element’s height. This method can be particularly useful for centering an element within the viewport or a div that has a variable height.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
  
    <title>Centering an Element Vertically</title>
  
    <style>
        .container {
            position: relative;
            height: 100vh;
        }
  
        #centerElement {
            position: absolute;
        }
    </style>
</head>
  
<body>
    <div class="container">
        <div id="centerElement">
            Welcome to w3wiki
        </div>
    </div>
  
    <script>
        $(document).ready(function () {
            var containerHeight = $('.container').height();
            var elementHeight = $('#centerElement').outerHeight();
            var marginTop = (containerHeight - elementHeight) / 2;
            $('#centerElement').css('top', marginTop + 'px');
        });
    </script>
</body>
  
</html>


Output

How to Center an Element in jQuery ?

Centering elements in a webpage is a common task for web developers, often involving CSS. However, certain scenarios might require dynamically centering elements using JavaScript or jQuery, especially when dealing with dynamic content sizes or responsive designs. jQuery, a fast, small, and feature-rich JavaScript library, simplifies the process of HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. In this article, we will explore how to center an element horizontally, vertically, or both, using jQuery.

Similar Reads

Prerequisites

To follow along with these examples, ensure you have jQuery included in your project. You can include jQuery by adding the following script tag in the section of your HTML document:...

Centering an Element Horizontally

To center an element horizontally within its parent container, you can set the element’s left margin to auto. This method works well when the element’s display property is set to block....

Centering an Element Vertically

...

Centering an Element Both Horizontally and Vertically

Centering an element vertically requires calculating the top margin based on the parent’s height and the element’s height. This method can be particularly useful for centering an element within the viewport or a div that has a variable height....