Summary of front-end HTML&CSS interview questions

Table of contents

box model

BFC

clear float

Six ways of position positioning

The method of centering elements up, down, left, and right

flex layout

two columns. The holy grail, the double-wing layout

Common block-level, line-level, empty elements

css Hack

The difference between src and href

The difference between link and @import

New Features of HTML5 and CSS3

browser compatible


box model

In our HTML page, each element can be regarded as a box, and this box is composed of four parts: content area (content), inner margin (padding), border area (border), and outer border area ( margin )

Standard box model (non-IE browsers)

box-sizing: content-box; the total width of a block (the width of the page) = width + margin (left and right) + padding (left and right) + border (left and right)

Weird box model (IE browser)

box-sizing: border-box; total width of a block = width + margin (left and right) (that is, width already includes padding and border values)

js box model

element.offsetParent _

Gets the nearest parent element with positioning

element.offsetLeft _

The distance relative to the left side of the parent element

element.offsetWidth _

Get the width occupied by the element itself, including content, border and padding

element.offsetHeight _

Get the height occupied by the element itself, including content, border and paddind

element.clientTop¶ _

Gets the size of the upper border of the element

element.clientLeft _

Gets the size of the left border of the element

element.clientWidth _

The obtained element includes padding and the width of the content, without borders

element.clientHeight _

The obtained element contains padding, the height of the content, without border

window.innerWidth Get the width and height of the browser enabled area

How to get and set the content width and height of the box

IE: dom.currentStyle.width/height

Non-IE: window.getComputedStyle(dom).width/height


var obj = document.getElementById("box");

var style = null;
if (window.getComputedStyle) {
    style = window.getComputedStyle(obj, null);    // 非IE
} else { 
    style = obj.currentStyle;  // IE
}
alert("width=" + style.width + "\nheight=" + style.height);

BFC

What is BFC

BFC means " 块级格式化上下文". BFC is an independent layout environment, which protects the internal elements from external influences and does not affect the external. BFC is a CSS layout method

How to trigger BFC

overflow: auto/ hidden;

position: absolute/ fixed;

float: left/ right;

display: inline-block/ table-cell/ table-caption/ flex/ inline-flex

Application of BFC

1 can be used for adaptive layout

Using this principle of BFC, a two-column layout can be realized, with fixed width on the left and self-adaptation on the right. Will not affect each other, even if the heights are not equal.

Add float to the left box, add overflow:hidden to the right box; turn it into a BFC, you can eliminate the influence of the external left box on him due to floating

2 can clear the float

When a child element in a parent element is set to float, the height of the parent element is not set. At this time, the child element is out of the document flow, and the parent element cannot perceive the height of the child element, causing the parent element to collapse.
At this time, adding overflow: hidden / auto to the parent element and turning it into BFC can solve this problem.

3 Solve vertical margin overlap

Add an empty element in the middle, set the element overflow:hidden

clear float

Why clear the float

Clear floating is mainly to solve the problem that the internal height of the parent element is 0 due to the floating of the child element

method to clear float

1. Extra label method:  for whom to clear the float, add an additional blank label after it

<div class="fahter">
        <div class="big">big</div>
        <div class="small">small</div>
        <div class="clear">额外标签法</div>
</div>


.clear{
        clear:both;
    }

 2. The parent adds the overflow method:

.fahter{
    width: 400px;
    border: 1px solid deeppink;
    overflow: hidden;
}

3. Use the after pseudo-element to clear the float:


 
<body>
    <div class="father clearfix">
        <div class="big">big</div>
        <div class="small">small</div>
        <!--<div class="clear">额外标签法</div>-->
    </div>
    
</body>



.clearfix:after{
        content: "";
        display: block;
        height: 0;
        clear:both;
    }
    .clearfix{
        *zoom: 1;/*ie6清除浮动的方式 *号只有IE6-IE7执行,其他浏览器不执行*/
    }

4. Use the before and after double pseudo-elements to clear the float: the usage is the same as above

Six ways of position positioning

static No positioning, can be used to cancel the previous positioning
relative Relative positioning, relative to its own alignment, the element does not fall off the label, and still occupies a place
absolute

Absolute positioning, child and father, positioning according to the parent element with positioning, if there is no parent element, look for it from the superior until the body

Off-label does not occupy space

fixed Fixed positioning, always for body positioning, off-label does not occupy space
you inherit Inherit the positioning of the parent element
sticky Sticky positioning, ceiling effect, automatically stick to the head when it touches the head, and the positioning is invalid if it does not touch the head

The method of centering elements up, down, left, and right

1 Child and father, the child element sets top and left to 50%, and then you can use merge-top/left to -50% each, or you can use transfrom to shift its own x and y axes by -50%

2 Use flex elastic layout

3 After the child is separated from the father, set the offset of the top/left/bottom/right of the child element to 0, and then set the margin to auto

flex layout

Basic concept of flex

In 2009, W3C proposed a new solution - Flex layout, which can implement various page layouts in a simple, complete and responsive manner. It is currently supported by all browsers, which means that it is now safe to use this feature.

The elements that adopt the Flex layout are called the Flex container (flex container), or "container" for short. All its child elements automatically become members of the container, called flex items (flex item), referred to as "items"

After setting to Flex layout, the child element's float, clear,positionand vertical-alignattributes will be invalid

Enable flex layout

display:flex

flex container properties

flex-direction

  property determines the orientation of the main axis (i.e. the direction in which items are arranged

  • row(default): The main axis is horizontal and the origin is at the left end.
  • row-reverse: The main axis is horizontal, and the starting point is at the right end.
  • column: The main axis is in the vertical direction, and the starting point is at the upper edge.
  • column-reverse: The main axis is in the vertical direction, and the starting point is at the bottom edge.

flex-wrap

Set whether the item wraps

* nowrap(default): no line breaks.

* wrap: Line break, the first line is above.

flex-flow

is a shorthand for flex-directionattribute and attribute, and the default value isflex-wraprow nowrap

justify-content

Defines the alignment of items on the main axis

  • flex-start(default): left-aligned
  • flex-end: right align
  • center: centered
  • space-between: Both ends are aligned, and the spacing between items is equal.
  • space-around: Equal spacing on both sides of each item. Therefore, the spacing between items is twice as large as the spacing between items and borders

align-items

定义项目在侧轴上如何对齐  一根侧轴的情况下

  • flex-start:交叉轴的起点对齐。
  • flex-end:交叉轴的终点对齐。
  • center:交叉轴的中点对齐。
  • baseline: 项目的第一行文字的基线对齐。
  • stretch(默认值):如果项目未设置高度或设为auto,将占满整个容器的高度

align-content

定义了多根侧轴线的对齐方式。

  • flex-start:与交叉轴的起点对齐。
  • flex-end:与交叉轴的终点对齐。
  • center:与交叉轴的中点对齐。
  • space-between:与交叉轴两端对齐,轴线之间的间隔平均分布。
  • space-around:每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍。
  • stretch(默认值):轴线占满整个交叉轴

flex项目的属性

order 定义项目的排列顺序。数值越小,排列越靠前,默认为0
flex-shrink

定义了项目的缩小比例

默认为1,即如果空间不足,该项目将缩小

设置为0,项目不会缩小

flex-basis 定义了在分配多余空间之前,项目占据的主轴空间
flex flex-growflex-shrink 和 flex-basis的简写,默认值为0 1 auto

两栏。圣杯,双飞翼布局

两栏布局

  • 左边浮动,右边加oveflow:hidden;变成BFC清除左侧浮动元素影响

三栏布局

  • 圣杯布局和双飞翼布局两者的功能相同,都是为了实现一个两侧宽度固定,中间宽度自适应的三栏布局。(中间先加载渲染)
圣杯布局来源于文章In Search of the Holy Grail,
而双飞翼布局来源于淘宝UED。
虽然两者的实现方法略有差异,
不过都遵循了以下要点:

* 两侧宽度固定,中间宽度自适应
* 中间部分在DOM结构上优先,以便先行渲染
* 允许三列中的任意一列成为最高列
* 只需要使用一个额外的<div >外层 标签

圣杯布局

1 主体部分是由主体container包裹的center,left,right三列,其中center定义在最前面

2 主体设置 padding-left: 200px; padding-right: 150px; 为左右两列预留出相应的空间

3 随后分别为三列设置宽度与浮动,同时对footer设置清除浮动

4 使用负外边距,将left放置到之前预留出的位置上

5 使用position: relativeright: 200px将left的位置在原有位置基础上左移200px,以完成left的放置

6 右侧同样

优点:
(1)兼容性好,兼容若有主流浏览器,包括万恶的IE6
(2)可以实现主要内容的优先加载

双飞翼布局

1 双飞翼布局的DOM结构与圣杯布局的区别是用container仅包裹住center,另外将.column类从center移至container上。

2 将container,left,right设置为float: left,而在container内部,center由于没有设置浮动,所以其宽度默认为container的100%宽度,通过对其设置margin-leftmargin-right为左右两列预留出了空间

3 将right通过margin-left放置到预留位置

4 左侧同样

总结

圣杯布局在DOM结构上显得更加直观和自然,且在日常开发过程中,更容易形成这样的DOM结构

而双飞翼布局在实现上由于不需要使用定位,所以更加简洁,且允许的页面最小宽度通常比圣杯布局更小

常见的块级、行级、空元素

  • 行内元素有:span a b i select strong
  • 块级元素有:div p h1-h6 ul table from ul ol li dl dt dd…
  • 空元素(没有内容): <br> <hr> <img> <input> <link> <meta>

css Hack

CSS样式中加入一些特殊的符号,让不同的浏览器识别不同的符号以达到应用不同的CSS样式的目的。用来兼容IE

条件Hack

<!--[if IE]>
    <p>你在非IE中将看不到我的身影</p>
<![endif]-->

只有在IE可以被解析,其他浏览器都是当做注释

属性Hack

*color:#f00; / * For IE7 * / 
_color:#ff0; /*  For IE6  */ }

IE6能识别下划线“”和星号“”,
IE7能识别星号“
”,但不能识别下划线”

选择符Hack

* html .test{color:#090;} /* For IE6 and earlier */
*+html .test{color:#ff0;} /* For IE7 */

比如IE6能识别 *html .class{}

IE7能识别*+html .class{}

写CSS hack需要遵循以下三条原则

  • 有效: 能够通过 Web 标准的验证
  • 只针对太古老的/不再开发的/已被抛弃的浏览器, 而不是目前的主流浏览器
  • 代码要丑陋。让人记住这是一个不得已而为之的 Hack, 时刻记住要想办法去掉

滥用hack会导致浏览器更新之后产生更多的兼容性问题。因此,并不推荐使用CSS hack来解决兼容性问题。 

src与href的区别

href 是指向网络资源所在位置,建立和当前元素之间的链接,用于超链接。

src是指向外部资源的位置

在请求src资源时会将其指向的资源下载并应用到文档内,当浏览器解析到该元素时,会暂停其他资源的下载和处理,直到将该资源加载、编译、执行完毕,类似于将所指向资源嵌入当前标签内

link与@import区别

页面中使用CSS的方式主要有3种:行内添加定义style属性值,页面内嵌调用和外面链接调用,其中外面引用有两种:Link引入和@import导入,两者都是外部引用CSS的方式,但是存在一定的区别:

  1. link是 标签,除了加载CSS外,还可以定义RSS等其他事务;@import属于CSS范畴,只能加载CSS。
  2. link引用CSS时,在页面载入时同时加载;@import需要页面网页完全载入以后加载。
  3. link是HTML标签,无兼容问题;@import是在CSS2.1提出的,低版本的浏览器不支持。
  4. link支持使用Javascript控制DOM去改变样式;而@import不支持。
  5. link方式的样式的权重 高于@import的权重;

HTML5与CSS3的新特性

css3

常规选择器

:last-child   选择元素最后一个孩子 

:first-child   选择元素第一个孩子 

:nth-child(1)   按照第几个孩子给它设置样式 

:disabled    属性选择器  选择每个禁用的dom元素

伪类选择器

a:link {color: #FF0000}  未访问的链接 

a:visited {color: #00FF00}   已访问的链接

a:hover {color: #FF00FF}    鼠标移动到链接上

伪元素选择器 ::before {}   选择器在被选元素的前面插入内容和定义css
::after {}      选择器在被选元素的后面插入内容和定义css
:first-letter   选择该元素内容的首字母  
:first-line     选择该元素内容的首行  
背景 background-size:规定背景图片的尺寸
background-origin:规定背景图片的定位区域 
边框 border-radius: 圆角
box-shadow / text-shadow: 阴影
border-image: 边框图片
文本效果

text-shadow    向文本添加阴影

text-outline      规定文本的轮廓

text-overflow   规定当文本溢出包含元素时发生的事情

text-wrap        规定文本的换行规则

渐变效果

background-image: linear-gradient(线性渐变)

background-image: radial-gradient(径向渐变

变形

transform:rotate             旋转

transform:scale             缩放

transform:translate        位移

过渡 transition : 过度的地方(color/width等) ,时间(1s/.5s) , 状态( linear / ease 等)
动画

@keyframes  定义动画名称及动画的行为

animation  设置动画相关值

animation-name: fadeIn  调用动画

HTML5

语义化标签

header  定义了文档的头部区域

footer    定义了文档的尾部区域

nav        定义文档的导航

section  定义文档中的结构标签

article    定义页面独立的内容区域

aside     定义页面的侧边栏内容

表单类型增强

color    主要用于选取颜色

date     从一个日期选择器选择一个日期

email   包含 e-mail 地址的输入域

month  选择一个月份

search  用于搜索域

url        URL 地址的输入域

新增的表单属性

placehoder    简短的提示信息

min 和 max   设置元素最小值与最大值

required        是一个 boolean 属性。要求填写的输入域不能为空

html5 新事件

onresize    当调整窗口大小时触发

ondrag      当拖动元素时触发

onscroll     当滚动元素滚动元素的滚动条时触发

onerror     当错误发生时触发

onmousewheel  当转动鼠标滚轮时触发

音频视频标签

audio  音频标签

video  视频标签

本地存储

localStorage    永久存储,除非手动删除或代码删除

sessionStorage  关闭当前会话删除

浏览器兼容

不同的浏览器,浏览器的内核是不同的,所以各个浏览器对网页的解析存在一定的差异

浏览器的内核分为两种,渲染引擎,js引擎,所以,兼容问题一般是指css兼容 js兼容

css的兼容

问题: 不同浏览器的标签默认的margin和padding不同

解决方案:

1 通配符 * 设置内外边距为0

2 全局引入一个官方的样式重置表

问题:css3的新属性不兼容

解决方案:加浏览器的前缀来解决低版本浏览器不兼容问题

-moz- 火狐浏览器 
-webkit- 谷歌浏览器 /  苹果浏览器等使用Webkit引擎的浏览器
-o- 欧朋浏览器
-ms- IE浏览器

都有什么css3不兼容

定义关键帧动画 @keyframes
css3中的变形(transform)、过渡(transtion)、动画(animation)
border-radius 圆角
box-shadow  盒子阴影
flex  弹性布局
....

问题:块属性标签flot后,又有横行的margin情况下,IE 浏览器margin加倍的问题

解决方案:使用 display:inline 将这个块转换为行内元素

问题:. 设置较小高度标签(一般小于10px),在IE6,IE7中高度超出自己设置高度

解决方案:

  1. 给超出高度的标签设置overflow:hidden;
  2. 或者设置行高line-height 小于你设置的高度。

问题:IE浏览器div最小宽度和高度的问题

解决方案:

#box{
  width: 80px;
  height: 35px;
  }
html>body #box{
 width: auto;
 height: auto; 
 min-width: 80px; 
 min-height: 35px;
 }

问题:超链接访问过后hover样式就不出现的问题

解决方案:将四个伪类选择器按照固定的顺序排列使用

a:link {}      // 未访问前
a:visited {}   // 访问之后
a:hover {}     // 鼠标划过
a:active {}    // 点击不松开的时候

问题:图片默认有间距,使用通配符也无法清除

解决方案:

1 给所有图片设置flot-left

2 因为是写代码时不在一行,默认羽有个文字间距,用一个div包裹,设置 font-size:0 即可

浏览器css兼容的常用方法:css Hack

JS的兼容

问题:事件绑定的不同

IE:   dom.attachEvent();
标准浏览器: dom.addEventListener(‘click',function(event){ },false);

解决方案:使用 if 判断当前浏览器或者 try catch 

var x = document.getElementById("myBtn");

if (x.addEventListener) {   //所有主流浏览器,ie9+

    x.addEventListener("click", myFunction);

} else if (x.attachEvent) {      // IE 8 及更早 IE 版本

    x.attachEvent("onclick", myFunction);

}


或

var x = document.getElementById("myBtn");

try {
  x.addEventListener("click", myFunction);
} catch(x.attachEvent){
  x.attachEvent("onclick", myFunction)
}

问题:event事件对象问题

火狐不支持不传递形参,直接接受event为事件对象

解决方案:在事件里做一个 || 来兼容

    document.onclick=function(ev){  //谷歌火狐的写法,IE9以上支持,往下不支持;
        var e=ev;
    }

    document.onclick=function(){    //谷歌和IE支持,火狐不支持;
        var e=event;
    }

    document.onclick=function(ev){    //兼容写法;
        var e=ev||window.event;
    }

Problem: event.target (event source object) problem

IE:  event.srcElement
Standard browsers: event.target

Solution: judge the current browser by if or try or ternary expression

event = event.srcElement?event.srcElement:event.target;

Problem: The non-interline style values ​​of the obtained elements are different, that is, the width and height of the box whose width and height are automatically expanded are not set

IE:  dom.currentStyle['width'] 
standard browser: window.getComputedStyle(obj, null)['width']

Solution: judge the current browser by if or try

 
  function getStyle(obj,attr){
      if(obj.currentStyle){
         //兼容IE
          return obj.currentStyle[attr];
      }else{
         //非IE,
     return window.getComputedStyle(obj, null)[attr]; 
      }
   }

Problem: Prevent event bubbling and default behavior

w3c  prevents bubbling    e.stopPropagation()         prevents default behavior     e.preventDefault() 

IE      prevents bubbling  e.cancelBubble=true        prevents the default behavior     e.returnValue=false 

Solution: judge the current browser by if or try

//js阻止事件传播,这里使用click事件为例
    document.onclick=function(e){
        var e=e||window.event;
        if (e.stopPropagation) {
            e.stopPropagation();//W3C标准
        }else{
            e.cancelBubble=true;//IE....
        }
    }

Problem: ajax compatibility

IE:       ActiveXObject
Other:  xmlHttpReuest

Solution: judge the current browser by if or try

var oAjax = null;
			
if(window.XMLHttpRequest){

   // 标准浏览器
   oAjax = new XMLHttpRequest();				
		
}else{

   //只支持IE6浏览器
   oAjax = new ActiveXObject("Microsoft.XMLHTTP");	
			
}

Click to view the specific package code

Guess you like

Origin blog.csdn.net/hjdjhh/article/details/122330362