CSS差缺补漏之《高频面试题 | 您所在的位置:网站首页 › word2003上下对齐 › CSS差缺补漏之《高频面试题 |
面试中经常会被问到如何使元素水平垂直居中,有哪些方法可以做到? 针对此问题,特意总结如下~ 方法一: 定位(主要是值子绝父相)与margin负值配合----依赖于子元素宽/高 (使用绝对定位或固定定位后,所有元素,不管是行内元素还是行内块元素、块状元素,都可以定义宽高) 该方法适合子元素宽/高已知的情况~ .box { width: 200px; height: 200px; background-color: rgb(220, 230, 245); /* 父相 */ position: relative; } .box1 { width: 100px; height: 100px; background-color: yellow; position: absolute; /* 定位距离上面50% */ top: 50%; /* 定位距离左侧50% */ left: 50%; /* 定位在往下退自身高度的50%,即100*50% = 50px */ margin-top: -50px; /* 定位在往左退自身高度的50%,即100*50% = 50px */ margin-left: -50px; } 方法二: 定位(主要是值子绝父相)与变换负值配合----不依赖于子元素宽/高 (使用绝对定位或固定定位后,所有元素,不管是行内元素还是行内块元素、块状元素,都可以定义宽高) 该方法在子元素宽/高已知或未知的情况下都适合~ 很好很好很好很好很好很好很好很好很好很好 .box { width: 200px; height: 200px; background-color: rgb(220, 230, 245); position: relative; } .box1 { background-color: yellow; position: absolute; top: 50%; left: 50%; /* box1左移自身宽度的50% 上移自身高度的50% */ transform: translateX(-50%) translateY(-50%); } 方法三:定位与margin: auto配合 该方法适合于子元素宽/高已知的情况~ .box { width: 200px; height: 200px; background-color: rgb(220, 230, 245); /* 父相 */ position: relative; } .box1 { width: 100px; height: 100px; background-color: yellow; position: absolute; /* 以下都不可缺省 */ left: 0; top: 0; right: 0; bottom: 0; margin: auto; }
方法四:利用flex布局 (使用flex布局后,所有元素,不管是行内元素还是行内块元素、块状元素,都可以定义宽高) 该方法适合于宽/高已知/未知的情况~ .box { width: 200px; height: 200px; background-color: rgb(220, 230, 245); display: flex; /* 设置主轴方向居中 */ justify-content: center; /* 设置侧轴方向居中 */ align-items: center; } .box1 { width: 100px; height: 100px; background-color: yellow; }方法五: 针对行内元素的居中对齐方法 单行文本(给父元素加上): 水平居中: text-align: center 垂直居中: height = line-height 很好 .box { width: 200px; height: 200px; line-height: 200px; background-color: rgb(220, 230, 245); text-align: center; } .box1 { background-color: yellow; }方法六: 针对行内元素的居中对齐方法 多行文本: display: table(给父元素加上) display: table-cell(给子元素加上) vertical-align: middle(给子元素加上) text-aline: center(给子元素加上) .box { width: 200px; height: 200px; background-color: rgb(220, 230, 245); display: table; } .box1 { display: table-cell; vertical-align: middle; text-align: center; }方法七: 针对行内元素的居中对齐方法 多行文本: display: grid(给父元素加上) margin: auto(给子元素加上) text-aline: center(给子元素加上) .box { width: 200px; height: 200px; background-color: rgb(220, 230, 245); display: grid; } .box1 { background-color: yellow; margin: auto; text-align: center; } 以上就是垂直居中布局的所有方案~点赞收藏哦~
|
CopyRight 2018-2019 实验室设备网 版权所有 |