方式一:
.pdiv{ width: 500px; height: 400px; margin: 100px auto; border: 1px solid green; position: relative; } .div{ width: 300px; height: 100px; line-height: 100px; text-align: center; border: 1px solid red; position: absolute; top: 50%; left: 50%; margin: -50px 0 0 -150px; }
方式二:
.pdiv{ width: 500px; height: 400px; margin: 100px auto; border: 1px solid green; text-align: center; position: relative; } .div{ margin: auto; width: 300px; height: 100px; line-height: 100px; text-align: center; border: 1px solid red; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
方式三:
.pdiv{ width: 500px; height: 400px; margin: 100px auto; border: 1px solid green; display: flex; align-content: center; justify-content: center; } .div{ margin: auto; width: 300px; height: 100px; line-height: 100px; text-align: center; border: 1px solid red; }
方式四:
.pdiv{ width: 500px; height: 400px; margin: 100px auto; border: 1px solid green; text-align:center; position: relative; } .div{ width: 300px; height: 100px; line-height: 100px; text-align: center; border: 1px solid red; position: absolute; top:0;left: 0; right: 0; bottom: 0; margin: auto; }
方式五:
文章来源: Div垂直水平居中(CSS篇)