在使用auto中始终有许多疑惑,现将auto经常使用的几种用法总结如下:
width:auto
width的值是auto是最开始让我迷惑的地方。理解起来很简单,auto的意思是自动适应,也就是说整个元素会撑开至父元素的宽度。用公式表示就是:width+padding+margin=父width。
其中最容易混淆的就是width:100%了,用公式表示就是:width=父width,也就是说 width+padding+margin>父width。
margin:auto使元素左右居中
要使元素左右居中,只需要给元素设置宽度,然后将其margin的值为auto即可,则margin-left和margin-right会自动调节相等使得元素居中
<style>.center{width:700px;background-color:red;margin:0 auto;}</style><div class="center"><p>我是中国人</p><p>我爱我的国家</p><p>我从小生长在这里</p></div>
position:absolute和margin:auto联用使元素居中
有时候我们需要元素上下左右居中,而该元素的宽带和高度未知,可以使用绝对定位的方式来实现。
首先需要设置定位的父元素的position属性
<style>.outer{width: 300px;height: 300px;position: relative;border: 1px solid red;}</style><div class="outer"></div>
设置需要居中元素的position相关属性,将其top、bottom、left、right等都设置为零后,再将其margin值设置为auto,margin值将自动调整为满足top、bottom、left、right为零。此时,元素居中。
<style>.outer{width: 300px;height: 300px;position: relative;border: 1px solid red;}.inner{width: 100px;height: 100px;position: absolute;top: 0;right: 0;bottom: 0;left: 0;margin: auto;background-color: aqua;}</style><div class="outer"><div class="inner"></div></div>
