当前位置: 首页 > Web前端 > HTML

CSS - 垂直水平居中方法

时间:2023-04-02 13:17:24 HTML

参考链接整理搬运css垂直水平居中方法,区分内联元素与块级元素CSS垂直居中和水平居中【原】用css让一个容器水平垂直内联元素居中方法水平居中设置:行内元素 设置 text-align:center;Flex布局 设置display:flex;justify-content:center;(灵活运用)垂直居中设置:父元素高度确定的单行文本(内联元素),垂直居中:设置 height = line-height;父元素高度确定的多行文本(内联元素),垂直居中:先设置 display:table-cell 再设置 vertical-align:middle;如果在块级元素中包裹有多个行内元素,其中某个元素比较特殊,比如:大写加粗的文字、图片图标,垂直居中:该元素设置 { vertical-align: middle; }/* 同时对应 text-bottom/text-top 为下对齐/上对齐 */块级元素居中方法移动端,选用方法六和方法七,支持不定宽高的情况PC端,要考虑兼容性的话,可以选用方法四PC端,如果中间的元素高度不固定,可以选用方法五方法一:position加margin 兼容性:主流浏览器均支持,IE6不支持<!-- html --><div class="wrap"> <div class="content"></div></div>/**css**/.wrap { position: relative; width: 200px; height: 200px; background: pink;}.wrap .content{ position: absolute; width: 100px; height: 100px; background: skyblue; left: 0; right: 0; top: 0; bottom: 0; margin: auto;}方法二: diaplay:table-cell 兼容性:由于display:table-cell的原因,IE67不兼容<!-- html --><div class="wrap"> <div class="content"></div></div>/*css*/.wrap{ width: 200px; height: 200px; background: pink; display: table-cell; vertical-align: middle; text-align: center;}.content{ display: inline-block; vertical-align: middle; width: 100px; height: 100px; background: skyblue;}方法三:position加 transform 兼容性:ie9以下不支持 CSS3新属性transform,移动端表现较好<!-- html --><div class="wrap"> <div class="content"></div></div>/* css */.wrap { position: relative; background: pink; width: 200px; height: 200px;}.content{ position: absolute; background: skyblue; top:50%; left:50%; -webkit-transform:translate(-50%,-50%); transform:translate(-50%,-50%); width: 100px; height: 100px;}方法四:position(固定宽高) 兼容性:适用于所有浏览器<!-- html --><div class="wrap"> <div class="content"></div></div>/* css */.wrap { background: pink; width: 200px; height: 200px; position: relative;}.content{ background: skyblue; position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; margin-left:-50px; margin-top:-50px;}方法五:兼容低版本浏览器,不固定宽高<!-- html --><div class="table"> <div class="tableCell"> <div class="content">不固定宽高,自适应</div> </div></div>/*css*/.table { height: 200px;/*高度值不能少*/ width: 200px;/*宽度值不能少*/ display: table; position: relative; float:left; background: pink;} .tableCell { display: table-cell; vertical-align: middle; text-align: center; *position: absolute; padding: 10px; *top: 50%; *left: 50%;}.content { *position:relative; *top: -50%; *left: -50%; background: skyblue;}方法六:flex;align-items: center;justify-content: center 适合移动端<!-- html --><div class="wrap"> <div class="content"></div></div>/* css */.wrap { background: pink; width: 200px; height: 200px; display: flex; /*垂直居中*/ align-items: center; /*水平居中*/ justify-content: center;}.content{ background: skyblue; width: 100px; height: 100px;}方法七:display:flex;margin:auto 适合移动端<!-- html --><div class="wrap"> <div class="content"></div></div>/* css */.wrap { background: pink; width: 200px; height: 200px; display: flex; }.content{ background: skyblue; width: 100px; height: 100px; margin: auto;}