How would you center a child div within a parent div?

To center a child div within a parent div using JavaScript and HTML, you can follow these steps:

  1. Create a parent div in HTML with a specific width and height.
<div id="parentDiv" style="width: 300px; height: 200px; border: 1px solid black;">

  1. Create a child div inside the parent div.
<div id="childDiv" style="width: 100px; height: 100px; background-color: red;">
</div>

  1. Use JavaScript to center the child div within the parent div by setting its position to “absolute” and adjusting the top, left, bottom, and right properties.
<script>
var parentDiv = document.getElementById("parentDiv");
var childDiv = document.getElementById("childDiv");
childDiv.style.position = "absolute";
childDiv.style.top = "50%";
childDiv.style.left = "50%";
childDiv.style.transform = "translate(-50%, -50%)";
</script>

By setting the child div’s position to “absolute” and using the “top”, “left”, and “transform” properties, we can center it both horizontally and vertically within the parent div. The “translate(-50%, -50%)” transform property moves the child div 50% of its own width and height in the opposite direction, effectively centering it.

Note: Make sure to place the JavaScript code either at the end of the HTML body or inside a window.onload event to ensure that the DOM elements are loaded before accessing them.