注意:曾全职考公,空窗期一年,沉淀学习,重返赛道。
注意:有理解错、说错的地方,请各路大佬留言讨论,我好改进,感谢!!!
目录
- relative 和 absolute
- 居中对齐
- 水平居中
- 垂直居中
relative 和 absolute
relative
将元素相对于其正常位置进行偏移,而不脱离文档流。该元素仍然占据它原本的空间,但它可以通过top、right、bottom和left属性来调整其位置。
特点
- 不脱离文档流:元素仍然保持在文档流中,并占据原来的空间。
- 偏移量:偏移量是依据自身定位进行计算的。
- 包含块:通常是其最近的块级祖先元素,但与确定元素位置无关。
- 堆叠上下文:不会创建新的堆叠上下文(除非它同时设置了
z-index和opacity: 值小于1,或者其transform属性非none),但它可以参与其父元素或祖先元素的堆叠上下文。
absolute
将元素从文档流中脱离出来,并相对于其最近的已定位(即 position 不是 static)祖先元素进行定位。如果没有这样的祖先元素,那么它会相对于初始包含块(通常是<html>)进行定位。
特点
- 脱离文档流:元素从文档流中脱离出来,不占据空间,不会影响其他元素的布局。
- 偏移量:偏移量是相对于其最近的已定位(即 position 不是 static)祖先元素进行计算的。如果没有这样的祖先元素,那么它会相对于初始包含块(通常是
<html>)进行定位。 - 堆叠上下文:会创建一个新的堆叠上下文,这可能会影响
z-index属性的表现。 - 包含块:通常是其最近的已定位祖先元素。如果没有这样的祖先元素,那么初始包含块(即
<html>)将成为其包含块。 - 宽度和高度:默认情况下,宽度和高度是由其内容决定的,除非明确指定宽度和高度。
居中对齐
1. 水平居中
/* 子元素为 inline 和 inline-block 元素 */
.parent {
text-align: center;
}
/* 子元素为 block 元素 */
.child {
margin: auto;
}
/* 子元素为 absolute 元素 */
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
}
/* 方法1:child-1 */
.child-1 {
width: 100px; /* 缺点:需要知道该元素的 width */
margin-left: -50px; /* 该值的绝对值为 width 的一半 */
}
/* 方法2:child-2 */
.child-2 {
/* 缺点:若要兼容老的浏览器,谨慎使用 */
transform: translateX(-50%);
}
/* 父元素为 flex 元素,子元素要求居中 */
.parent {
display: flex;
justify-content: center;
// justify-content: space-around; /* 只有一个子元素时 */
}
/* 父元素为 grid 元素,子元素要求居中 */
.parent {
display: grid;
justify-content: center;
}
2. 垂直居中
/* 子元素为 inline 和 inline-block 元素 */
.child {
height: 20px;
line-height: 20px; /* line-height 的值等于 height 值 */
}
/* 子元素为 absolute 元素 */
.parent {
position: relative;
}
.child {
position: absolute;
}
/* 方法1:child-1 */
.child-1 {
top: 50%;
height: 100px; /* 缺点:需要知道该元素的 height */
margin-top: -50px; /* 该值的绝对值为 height 的一半 */
}
/* 方法2:child-2 */
.child-2 {
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
/* 方法3:child-3 */
.child-3 {
top: 50%;
/* 缺点:若要兼容老的浏览器,谨慎使用 */
transform: translateY(-50%); /* 50% 为子元素自身一半的高度 */
}
/* 父元素为 flex 元素,子元素要求居中 */
.parent {
display: flex;
align-items: center;
}
/* 父元素为 grid 元素,子元素要求居中 */
.parent {
display: grid;
align-items: center;
// place-items: center; /* 简写,同时实现水平和垂直居中 */
}
/* 父元素为 table 元素,子元素中的 .content 要求居中 */
.parent {
display: table;
width: 100%;
height: 100px;
}
.child {
display: table-cell;
vertical-align: middle;
}
.content {
display: inline-block; /* 确保内容块级显示 */
}