1、css相关
1、绝对定位元素居中的原理
秘诀:绝对定位元素的布局由元素的三个因素决定:位置(top、bottom、left、right)、元素尺寸和margin。绝对定位元素在布局上呈现自适应的特点——位置和尺寸固定,则自适应margin值;位置和margin固定,则自适应尺寸。
实例:(1)位置和尺寸固定,margin:auto;
<div id='wrap'>
<div id='item1'></div>
</div>
#wrap {
width: 500px;
height: 500px;
border: 1px dotted black;
position: relative;
}
#item1 {
width: 100px;
height: 100px;
background-color: purple;
/* 核心代码 */
position: absolute;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
分析:
水平方向:
width(wrap)=margin(item)+width(item)+padding(item)+left(item)+right(item)
由于位置设置为 top: 0;bottom: 0;left: 0;right: 0; ,尺寸固定为 width: 100px;
height: 100px;,margin:auto;自适应,实际水平方向margin值为500-100 =400px,平均分配左右两侧,即为margin-left:200px;margin-right:200px;。垂直方向同理可得。可以看到在绝对定位元素中,若水平方向位置left与right值相等,那么margin-left: auto;margin-right:auto;可以让其相对于定位的祖先元素水平居中。
(2)位置和margin固定
<div id='wrap'>
<div id='item1'></div>
</div>
#wrap {
width: 500px;
height: 500px;
border: 1px dotted black;
margin: 0 auto;
position: relative;
}
#item1 {
background-color: purple;
/* 核心代码 */
position: absolute;
margin: 20px;
top:0;
bottom: 0;
left: 0;
right: 0;
}
分析:
在水平方向,由于right:0;left:0;并且margin-left:20px;margin-right:20px;各项相加和等于定位的祖先元素宽度,因此width的值为460px。