盒模型水平居中
方案一:
<style> * { margin: 0; padding: 0; } #test { position: absolute; left: 0; right: 0; bottom: 0; top: 0; margin: auto; width: 100px; height: 100px; background: #cccccc; text-align: center; line-height: 100px; } </style> <body> <div id="test">test</div> </body>
方案二:
<style> * { margin: 0; padding: 0; } #test { width: 100px; height: 100px; background: #cccccc; position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; text-align: center; line-height: 100px; } </style> <body> <div id="test">test</div> </body>
图片水平居中:
//利用伪元素
<style> * { margin: 0; padding: 0; } html,body{ height: 100%; } body{ text-align: center; } body::after{ content: ""; display: inline-block; height: 100%; vertical-align: middle; } img{ vertical-align: middle; } </style> </head> <body> <img src="https://placehold.it/200x200"> </body>