Home > Article > Web Front-end > How to achieve vertical and horizontal centering in css when the size of the element is not known (code)
The content of this article is about how to achieve vertical and horizontal centering (code) of elements of unknown size in CSS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Idea: Position the child elements absolutely, 50% from the top, 50% from the left, and then use css3 transform:translate(-50%; -50%)
Advantages: High-end, can be used in the webkit kernel Using
in the browser Disadvantages: The transform attribute is not supported under IE9
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>未知宽高元素水平垂直居中</title> </head> <style> .parent3{ position: relative; height:300px; width: 300px; background: #FD0C70; } .parent3 .child{ position: absolute; top: 50%; left: 50%; color: #fff; transform: translate(-50%, -50%); } </style> <body> <p class="parent3"> <p class="child">hello world-3</p> </p> </body> </html>
Related recommendations:
Code examples of CSS selectors and code examples of css priority
The above is the detailed content of How to achieve vertical and horizontal centering in css when the size of the element is not known (code). For more information, please follow other related articles on the PHP Chinese website!