<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> </style> </head> <body> <!-- 1.让行内元素居中:给其父元素添加text-align:cent --> <div style="text-align:center;"> <span style="background-color:aqua;">1</span> </div> <br> <!-- 2.给块级元素居中:设置宽度(如果不设置宽度的话,块级元素默认占满一行,无法居中),然后利用margin:0 auto居中 --> <div> <h3 style="width: 100px;height:20px;margin: 0 auto;background-color: pink;text-align: center;">2</h3> </div> <br> <!-- 3.浮动元素:通过位置,postion:relative;left:50%;margin-left:(负值元素宽度的一半) --> <div> <div style="float:left;position: relative;left: 50%;background-color: goldenrod;text-align: center;width: 100px;margin-left:-50px">3</div> </div> <!-- 4.定位元素:top:0;left:50%;margin-left:(负值的宽度的一半) --> <div> <div style="position:absolute;top:150px;left:50%;width:100px;margin-left:-50px;background-color: palegoldenrod;text-align: center;">4</div> </div> </body> </html>
运行效果: