Home > Article > Web Front-end > CSS to achieve horizontal and vertical centering of elements
In our actual project, there are many methods for vertical centering. For example, there are many pop-up box prompts contents on the mobile page. They are briefly organized as follows. I hope it can help. to everyone.
I have made a lot of pages, and I feel that the problem of vertical centering has always existed. I feel that some methods are relatively simple, and some need to be calculated based on the actual situation. What I have compiled is the method I have used in practice, which may not be the most practical. Comprehensive, but the practical effect is still good.
Stop talking nonsense and go straight to the code:
/* 常用的三种方法 */ /* 第一种 */ div{ width: 200px; height: 200px; margin: auto; background: pink; position: fixed; top: 0; left: 0; right: 0; bottom: 0; } /* 第二种 */ div{ width: 200px; height: 200px; background: green; position: fixed; top: 50%; left: 50%; margin-left: -100px; margin-top: -100px; } /* 第三种 */ div{ width: 200px; height: 200px; background: green; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
Go directly to the html part to implement it
Related recommendations:
Parsing of CSS control scroll bar style
Detailed example of CSS3 custom scroll bar style
Example of CSS setting div scroll bar style
The above is the detailed content of CSS to achieve horizontal and vertical centering of elements. For more information, please follow other related articles on the PHP Chinese website!