css面试题

2021-09-17 02:12

阅读:852

标签:ica   cell   enter   lex   ali   width   play   定位   com   水平垂直居中的几种方法 水平居中 1、如果是行内元素,只需在父元素设置 text-align: center; 即可。 2、块级元素,只需设置 margin: 0 auto; 即可。 如下元素结构: hello world 3、absolute + magin 定位位置为 left: 50%; 然后 margin-left: -50px; 向左偏移元素宽度的一半。 缺点:要知道元素的宽度 #wrap{ position: relative; } #box{ width: 100px; position: absolute; left: 50%; margin-left: -50px; } 4、absolute + translate 跟上面方法差不多,用 transform: translateX(-50%); 代替 margin-left,这样就不需要知道元素的宽度了。 缺点:transform 的兼容性(ie10) #wrap{ position: relative; } #box{ width: 100px; position: absolute; left: 50%; transform: translateX(-50%); } 5、absolute + margin auto 元素定位 left: 0; right: 0; margin: 0 auto; 即可。 #wrap{ position: relative; } #box{ width: 100px; position: absolute; left: 0; right: 0; margin: 0 auto; } 6、flex 弹性布局什么的最喜欢了。 缺点:flex 兼容性(ie11) #wrap{ display: flex; justify-content: center; } 垂直居中 垂直居中跟水平居中有很多相似的方法。 1、如果是单行文本,设置 line-height 即可。 2、absolute + magin 定位位置为 top: 50%; 然后 margin-top: -50px; 向上偏移元素高度的一半。 缺点:要知道元素的高度 #wrap{ position: relative; } #box{ height: 100px; position: absolute; top: 50%; margin-top: -50px; } 3、absolute + translate 跟上面方法差不多,用 transform: translateY(-50%); 代替 margin-top,这样就不需要知道元素的高度了。 缺点:transform 的兼容性(ie10) #wrap{ position: relative; } #box{ height: 100px; position: absolute; top: 50%; transform: translateY(-50%); } 4、absolute + margin auto 元素定位 top: 0; bottom: 0; margin: auto 0; 即可。 #wrap{ position: relative; } #box{ height: 100px; position: absolute; top: 0; bottom: 0; margin: auto 0; } 5、display: table-cell 在父元素设置 display: table-cell; 将普通元素变成 table 元素,再设置 vertical-align: middle; 垂直居中。 #wrap{ display: table-cell; vertical-align: middle; } 6、flex 缺点:flex 兼容性(ie11) #wrap{ display: flex; align-items: center; } 参考文章css面试题标签:ica   cell   enter   lex   ali   width   play   定位   com   原文地址:https://www.cnblogs.com/samfung/p/12319625.html


评论


亲,登录后才可以留言!