How to center a div with CSS and JavaScript

17
0

To center a div in HTML using CSS, you can use the margin property with the auto value.

Here is an example of how you can center a div with a fixed width:

<style>
  .center {
    width: 50%;
    margin: auto;
  }
</style>

<div class="center">
  <p>I am a centered div!</p>
</div>

To center a div in HTML using JavaScript, you can use the getBoundingClientRect method to get the dimensions of the div element and the window.innerWidth and window.innerHeight properties to get the dimensions of the viewport. Then you can use the style property to set the left and top properties of the div to center it horizontally and vertically.

Here is an example of how you can center a div using JavaScript:

<div id="myDiv">
  <p>I am a div that will be centered!</p>
</div>

<script>
  var div = document.getElementById("myDiv");
  var rect = div.getBoundingClientRect();
  div.style.left = (window.innerWidth - rect.width) / 2 + "px";
  div.style.top = (window.innerHeight - rect.height) / 2 + "px";
</script>

Keep in mind that the div element will need to have a fixed width and height for this method to work properly.

Leave a Reply

Your email address will not be published. Required fields are marked *