<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>盒子居中對齊</title> <style> .nav{ width: 300px; height: 300px; background-color: yellow; text-align: center; /*可以讓盒子的內容(文字 行內元素 行內塊元素)水平居中對齊*/ color: red; margin: 0 auto; /*盒子水平居中對齊常用的方法。上下是外邊距是0,auto:自動 的意思。 讓一個盒子居中只要保證左右外邊距都是auto就可以了。 有兩個前提條件: 1、必須是塊元素 2、必須給定width 還有兩種寫法: 第二種寫法: margin: auto; 第三中寫法:margin-left:auto; margin-right:auto; 效果都是一樣的 */ } </style> </head> <body> <div class="nav"> 盒子居中對齊 </div> </body> </html>