块级盒子水平居中对齐

利用外边距可以让盒子居中对齐,但必须满足: 1.盒子必须指定 width。 2.盒子的 左右外边距 都设置为 auto。

例:

<body>
		<div class="header">
			<span>里面的文字</span> <!-- 行内元素 -->
		</div>
		<div class="header2">
			<img src="images/01.png" /> <!-- 行内块元素 还有 input 和 单元格-->
		</div>
	</body>
.header {
          
   
				width: 900px;
				height: 200px;
				background-color: pink;
				margin: 0 auto;
				text-align: center;
			}

			img {
          
   
				width: 50px;
				height: 50px;
			}

			.header2 {
          
   
				width: 900px;
				height: 200px;
				background-color: pink;
				margin: 100px auto;
				text-align: center;
			}

margin: 0 auto; 开发中最常用这种写法.另外还有两种写法: margin-left: auto; 且 margin-right: auto; 或只写 margin: auto;

注意: 以上做法是让 块级元素 水平居中, 行内元素 或 行内块元素 水平居中给其父元素添加 text-align 即可。

效果: 可以合并写成:

.header {
          
   
				width: 900px;
				height: 200px;
				background-color: pink;
				margin: 100px auto;
				text-align: center;
			}

			img {
          
   
				width: 50px;
				height: 50px;
			}

把第二个类名也改成 class="header"

经验分享 程序员 微信小程序 职场和发展