本篇文章主要是总结几个前端面试常见的CSS面试题,希望对大家的面试有所启示。

css页面布局面试题(CSS面试常见问题)(1)

一、CSS实现水平居中和垂直居中的方法有哪几种?

1、水平居中

.son { display:inline-block; text-align:center; }

// 父布局的css 需要设置 overflow:hidden .father{ width:100%; height:200px; overflow:hidden;//不可缺少否则margin-top不生效 } .son{ width: 100px; height: 100px; margin:50px auto ; }

display:table-cell; /*IE8以上及Chrome、Firefox*/ vertical-align:middle; /*IE8以上及Chrome、Firefox*/

.father{ display:flex; justity-content:center; align-items:center; } .father{ display:flex; flex-direction:column;//改变主轴为cross axis justity-content:center; }

.father{ position:relative; width:60%; height:400px; } .son{ width:100px; height:160px; position:absolute; left:50%; top:50%; margin-left:-50px; margin-top:-80px; }

2、垂直居中

.son { height:60px; line-height:60px; // line-height需要和height保持一致 display:inline-height; }

二、absolute与fixed共同点与不同点

absoluate和fixed都是position属性的值类型。position规定元素的定位类型,取值类型如下:

fixed和absoluate相同点:

  1. 脱离文档流
  2. 覆盖非定位元素,上层显示

fixed和absoluate不同点:

  1. 相对定位的父级不同,fixed相对根节点,absoluate选择对于static定位以外的第一个父元素进行定位。
  2. 浏览器的滚动条不会影响fixed的定位位置,absoluate会被影响【由于第一个原因导致的】

三、清除浮动的方法

CSS中经常会出现使用了float浮动元素而导致页面中某些元素不能正确地显示。那么如何清除float的浮动带来的副作用呢?

1、在父元素中添加子元素,并为添加的子元素中添加clear,清除浮动

clear的取值如下:

<style> .clearfix { clear: both; } </style> <div class="box1"> <div class="content1">content1</div> <div class="clearfix"></div> </div> <div class="box2"> <div class="content2">content2</div> </div>

2、伪元素清除clearfix

给父级元素添加了一个:after伪元素,通过清除伪元素的浮动,达到撑起父元素高度的目的。

.clearfix:after{ content:""; display:block; visibility:hidden; clear:both; }

3、使用BFC清除

通过给父元素设置:overflow:auto或者overflow:hidden。让父元素高度被撑起来。

<style> .wrap{ width:500px; margin:0 auto; overflow:hidden; } .float{ width:200px; height:200px; float:left; } .nofloat{ width:300px; height:150px; overflow:hidden; } </style> <div class="wrap"> <div class="float">浮动</div> <div class="nofloat">清除浮动</div> </div>

四、什么是BFC?

BFC的官方定义是:BFC(Block Formatting Context)块格式化上下文, 是Web页面的可视CSS渲染的一部分,是块盒子的布局过程发生的区域,也是浮动元素与其他元素交互的区域。简单点来说就是帮我们帮BFC内的元素和BFC外的元素进行隔离,使其不会影响到外部元素。

BFC类型:

五、CSS和sass、LESS有什么区别?

CSS(层叠样式表)是一门非程序式语言,SASS是使用Ruby 编写,是一种对css的一种扩展提升,增加了规则、变量、混入、选择器、继承等等特性。可以理解为用js的方式去书写,然后编译成css。LESS受Sass的影响较大,但又使用CSS的语法,让大部分开发者和设计师更容易上手。简单点说就是less、sass是属于编译型CSS,需要通过编译最终生成CSS。区别如下:

六、rem 和 em 的区别?

em是一种相对长度单位,相对于自身元素的字号大小,如果没有设置就参照父容器的字号大小或浏览器默认字号大小。rem是CSS3的新标准也是一种相对长度单位,其相对于html根标签的字号大小。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> html{ font-size: 20px; } #box{ width: 10rem; height: 10rem; background: red; font-size:12px; } .remFont { font-size:1rem; } .emFont { font-size:1em; } </style> </head> <body> <div id="box"> <div class="remFont">字体大小20px</div> <div class="emFont">字体大小12px</div> </div> </body> </html>

,