To align an element both vertically and horizontally at the center of its parent element, you can use CSS flexbox,CSS Grid or Custom css with
position absolute. Here are examples of both approaches:
1. Using CSS Flexbox:
.parent {
display: flex;
justify-content: center; /* Horizontal centering */
align-items: center; /* Vertical centering */
}
In this example, the `.parent` class represents the parent element containing the element you want to center. By setting `display: flex` on the parent, its child elements become flex items. The `justify-content: center` property centers the child element horizontally, while `align-items: center` centers it vertically.
2. Using CSS Grid:
.parent {
display: grid;
place-items: center; /* Centers both horizontally and vertically */
}
Here, the `.parent` class uses CSS Grid by setting `display: grid`. The `place-items: center` property centers the child element both horizontally and vertically within the grid cell.
Remember to apply these styles to the parent element that contains the element you want to center. You can adjust the CSS selectors (`parent`) according to your HTML structure and class names.
3. Custom css with position absolute
.parent {
position: relative
}
.container {
position:absolute;
top: 50%;
left: 50%;
width:100px;
height:100px;
margin-left:-50px;
margin-top:-50px;
border: 1px solid #ccc;
background-color: #f3f3f3;
}
or
.parent {
position: relative
}
.container {
position:absolute;
top: 50%;
left: 50%;
width:100px;
height:100px;
transform:translate(-50%,-50%);
border: 1px solid #ccc;
background-color: #f3f3f3;
}
In this approach, the parent element should have a non-static position, such as position: relative, to serve as the reference for absolute positioning. The child element is positioned absolutely using position: absolute. By setting top: 50% and left: 50%, the element is moved to the center of its parent.
Finally, transform: translate(-50%, -50%) shifts the element back by 50% of its own width and height, effectively centering it.
You can also use margin-left and margin-top to shift the element by 50 percent, in this case it will be margin-left:-50px; and margin-top:-50px; as height and width of element is 100px
HTML:-
<body class="parent">
<div class="container">
<div class="item item-1">
1.Lorem Ipsum has been the industry's standard dummy text ev
</div>
</div>
</body>