前端-CSS学习笔记05-元素设置技巧

居中,隐藏,文字多余隐藏

1. 元素水平居中

1.1. 行内级元素

  • 设置在父元素中
1
text-align: center;

1.2. 块级元素

  • 设置在本元素中
  • 一般针对于固定宽度的盒子,如果大盒子没有设置宽度,默认占满父元素的宽度
1
margin: 0 auto;

1.3. 绝对定位

  • 设置在本元素中
  • 要求:父元素为相关定位/绝对定位,元素是有固定宽度的盒子
1
2
3
4
position: absolute;
left: 0;
right: 0;
margin: 0 auto;

1.4. flex布局

  • 设置在父元素中
1
2
display: flex;
align-items: center;

1.5. transform

  • 设置在本元素中

  • 一般用在父元素相对定位,子元素绝对定位

    • 元素向右位移父元素的50%
    • 元素向左位移自身的50%
    1
    2
    3
    4
    5
    position: absolute;
    left: 50%;
    top: 0;

    transform: translate(-50%,0);
  • 可以用margin-left:-50%;

    1
    2
    margin-left: 50%;
    transform: translate(-50%,0);

2. 元素垂直居中

2.1. 行内可替换元素

  • 设置line-height = height,可以取消上下间距
  • 对行内非替换元素无效
1
2
height: 50px;
line-height: 50px;

2.2. 绝对定位

  • 设置在本元素中
  • 要求:父元素为相关定位/绝对定位,元素是有固定高度的盒子
  • 脱离了标准流
1
2
3
4
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;

2.3. flex布局

  • 设置在父元素中
  • 导致所有子元素垂直居中
1
2
display: flex;
justify-content: center;

2.4. transform

  • 设置在本元素中

  • 一般用在父元素相对定位,子元素绝对定位

    • 元素向下位移父元素的50%
    • 元素向上位移自身的50%
    1
    2
    3
    4
    5
    position: absolute;
    left: 0;
    top: 50%;

    transform: translate(0,-50%);
  • 不要用margin-top:50%;

    • margin-top的百分比是 参考包含块的宽度(refer to the width of the containing block)
    • 如果父子元素的顶部线重叠,也会导致margin-top传递,父子元素同时向下移动

3. 元素隐藏

3.1. display:none

  • 元素不显示出来, 并且也不占据位置, 不占据任何空间(和不存在一样)
  • 开发中经常会通过display属性完成元素的显示隐藏切换
  • diaplay:none; 隐藏,display:block; 显示

3.2. visibility:hidden

  • 虽然元素不可见, 但是会占据元素应该占据的空间
  • 默认为visible, 元素是可见的

3.3. rgba(x,x,x,0)

  • rgba设置颜色, 将a的值设置为0
  • rgba的a设置的是alpha值, 可以设置透明度, 不影响子元素

3.4. opacity:0

  • opacity用于设置元素整体透明度

  • 属性值:0-1之间的数字

    • 1:表示完全不透明
    • 0:表示完全透明
  • 注意点:

    • 设置整个元素的透明度, 会影响所有的子元素

4. 多余的以…表示

4.1. 文字显示在一行

1
2
3
4
5
6
7
8
9
10
11
12
13
<style>
div{
width: 100px;
}
p{
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
</style>
<div>
<p>Hello World Hello World Hello World</p>
</div>

4.2. 文字显示在两行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<style>
div{
width: 100px;
}
p{
word-wrap: break-word;
display: -webkit-box;

/* 超过几行剩余的显示省略号 */
-webkit-line-clamp: 2;
/* webbox方向 */
-webkit-box-orient: vertical;

text-overflow: ellipsis;
overflow: hidden;
}
</style>
<div>
<p>Hello World Hello World Hello World</p>
</div>
本文结束  感谢您的阅读