块级元素水平居中
- 应用条件:盒子被指定width
- 方式:设置左右外距为auto,即
- margin:0 auto;(常用)
- margin-left:auto; margin-right:auto;
- margin-auto;
- eg.
- 不使用居中时:
<style> .block { width: 500px; height: 500px; background-color: chartreuse; /* margin: 0 auto; */ } </style> <body> <div class="block"></div> </body>
-
使用居中时:
<style> .block { width: 500px; height: 500px; background-color: chartreuse; margin: 0 auto; } </style> <body> <div class="block"></div> </body>
内联,行内块元素水平居中
- 须知:与块级元素水平居中区分,设置左右外边距为auto并不能使内联及行内块元素水平居中
- 方式:给父元素添加text-align: center;
- eg:
- 不使用居中
<style> .block { width: 500px; height: 500px; background-color: chartreuse; margin: 0 auto; } </style> <body> <div class="block"> <p>新年快乐</p> </div> </body>
- 使用居中
<style> .block { width: 500px; height: 500px; background-color: chartreuse; margin: 0 auto; text-align: center; } </style> <body> <div class="block"> <p>新年快乐</p> </div> </body>