前端面试题(持续复习中)

92 阅读2分钟

如何实现一个元素的水平垂直居中

1.flex垂直居中display: flex;

简单粗暴,兼容性需要IE10+,父元素高度需要指定,元素的宽高可以随内容适应

div{
  display: flex;
  align-items: center;
  justify-content: center;
}

2.定位+负边距和定位+CSS3位移

定位+负边距兼容性较好,能够兼容到IE6,元素的宽高需要固定

定位+CSS3位移由于使用了CSS3中的transform属性,需要IE9+浏览器元素宽高不需固定,可以随内容适应

div{
  position: relative;
  height: 300rpx;
  background: #333333;
}
/*定位+CSS3位移*/
.box{
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;  
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  background: #FFFFFF;
}
/*定位+CSS3位移*/
.box{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%); 
  width: 200px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  background: #FFFFFF;
}

3.grid垂直居中

CSS网格布局,使用较少,兼容一般般

div{
  display: grid
  align-items: center;
  justify-content: center;
  /*justify-items: center;
  align-items: center;*/
}

css优先级确定

!important优先级最高 js也无法修改

优先级关系:内联样式 > ID 选择器 > 类选择器 = 属性选择器 = 伪类选择器 > 标签选择器 = 伪元素选择器

如何清除浮动

clear清除浮动 {clear:both;height:0;overflow:hidden;}

给父级添加overflow:hidden 清除浮动方法

万能清除法 after伪类 清浮动(现在主流方法,推荐使用)

div:after{
    content:".";
    clear:both;
    display:block;
    height:0;
    overflow:hidden;
    visibility:hidden;
}
div{
    zoom:1
} 

边距重叠解决方案(BFC) BFC原理

BFC 即 Block Formatting Contexts (块级格式化上下文),它是页面中的一块渲染区域,并且有一套渲染规则,它决定了其子元素将如何定位,以及和其他元素的关系和相互作用。

只要元素满足下面任一条件即可触发 BFC 特性: body 根元素
浮动元素:float 除 none 以外的值
绝对定位元素:position (absolute、fixed)
display 为 inline-block、table-cells、flex
overflow 除了 visible 以外的值 (hidden、auto、scroll)