div实现内部元素居中的三种方式

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>实现内部元素居中的三种方式</title> <style> *{margin: 0; padding: 0;} h2{text-align: center; color: red;} h3{text-align: center; color: blue;} .clearfix:after{content: '';clear: both; display: block; overflow: hidden; height: 0;} /*方法一:传统方法通过固定宽度width: 1000px;和margin: 0 auto;来实现居中, *弊端:1.需要精确计算出box的宽度, * 2.当内部子元素需要增加或者减少的时候,这个宽度需要重新计算,比较麻烦。 * 3.需要使用clear来清除浮动,解决因浮动产生的外部元素无法获取高度的尴尬问题。 */ .box-wrap0{position: relative; width: 100%; height: 100px; text-align: center; padding: 20px; line-height: 30px;} .box-wrap0 .box{position: relative; width: 1000px; margin: 0 auto; border: red 1px solid;} .box-wrap0 .box-item{width: 200px; float: left; background: #dedede;} /* *方法二:1.最里面的元素使用内联元素布局,2.外部元素使用margin: 0 auto; 可以轻松实现居中对齐 */ .box-wrap1{position: relative; width: 100%; height: 100px; padding: 20px; text-align: center; line-height: 30px;} .box-wrap1 .box{position: relative; margin: 0 auto; border: red 1px solid;} .box-wrap1 .box-item{width: 200px; display: inline-block; background: #dedede;} /*内部元素为内联元素*/ /* *方法三:1.最外部元素使用text-align: center; 2.给需要居中的元素display: inline-block;变成内联元素 3.给需要居中的元素float: left;,可以轻松实现居中对齐 *优势:当内部元素需要增加或者减少时,仍然会自动居中 */ .box-wrap2{position: relative; width: 100%; text-align: center; margin-top: 50px; padding: 20px; line-height: 30px;} /* 内容居中显示:text-align: center;*/ .box-wrap2 .box{position: relative; display: inline-block; border: blue 1px solid;} /*需要居中的元素为内联元素*/ .box-wrap2 .box-item{width: 200px; float: left; margin: 0 10px; background: #dedede;} </style> </head> <body> <h2>实现内部元素居中的三种方式</h2> <div class="box-wrap0"> <h3>方法一:固定宽度</h3> <div class="box clearfix"> <div class="box-item">按钮1</div> <div class="box-item">按钮2</div> <div class="box-item">按钮3</div> <div class="box-item">按钮4</div> <div class="box-item">按钮4</div> </div> </div> <div class="box-wrap1"> <div class="box"> <h3>方法二:子元素为内联元素</h3> <div class="box-item">按钮1</div> <div class="box-item">按钮2</div> <div class="box-item">按钮3</div> <div class="box-item">按钮4</div> <div class="box-item">按钮4</div> </div> </div>