While developing website most of the time we face the issue to align particular section or element vertically and horizontally center to it's parent element. There are many ways to achieve this requirement but what if the child content is dynamic and unknown ?
There is a solution for that. Make two CSS classes. one for parent element and one for child element. Make parent element Position relative and child element position absolute to it's parent element and play with child element's top,left and transform properties to make child element horizontally and vertically center.
The best part of following code is that you can use only two CSS classes to align element vertically and horizontally center and middle of the section.
Following example can give much clear idea.
HTML:
There is a solution for that. Make two CSS classes. one for parent element and one for child element. Make parent element Position relative and child element position absolute to it's parent element and play with child element's top,left and transform properties to make child element horizontally and vertically center.
The best part of following code is that you can use only two CSS classes to align element vertically and horizontally center and middle of the section.
Following example can give much clear idea.
HTML:
<div class="container"> <div class="row"> <!-- parent container add .parent-center class --> <div class="col-md-12 parent-center"> <!-- child container add .child-center class --> <div class="child-center"> <h1>Vertically and horizontally center </h1> <h1>Vertically and horizontally center </h1> <h2>Add as main as element you want. </h2> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p> </div> </div> </div> </div>
CSS :
.col-md-12 { min-height:400px; background: linear-gradient(270deg, #003366, #b27000, #06617d, #067370); background-size: 800% 800%; } /* parent container css */ .parent-center { position: relative; } /* child container css */ .child-center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff; text-align: center; }
See the Pen css - Horizontally and vertically center element to it's container by Yashwant Patel (@yashwant) on CodePen.
Download Source
CSS - vertically and horizontally center align any element with its parent element
By yash →
Friday, March 18, 2016