<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
/*
一,水平居中
方法1 :行内元素 (父元素)text-align,(子元素)inline-block
.parent{text-align: center;}
.child{display: inline-block;}
总结:
优点:兼容性好,支持低版本浏览器
缺点:需要同时在父元素和子元素上设置
适用场景:子元素数量少(或只有一个),并且需要兼容低版本浏览器时使用,不受float影响
*/
.parent1 {
background: red;
height: 200px;
text-align: center;
}
.child1 {
background: blue;
display: inline-block;
width: 100px;
height: 100px;
}
/*
一,水平居中
方法2:块状元素 使用margin:0 auto来实现
.child{width:200px;margin:0 auto;}
优点:兼容性好
缺点:需要指定宽度
前提:用于子元素上,不受float影响
*/
.parent2 {
background: red;
height: 200px;
}
.child2 {
background: blue;
width: 100px;
height: 100px;
margin: 0 auto;
}
/*
一,水平居中
方法3:(子元素)display:table;margin:0 auto;
.child{display:table;margin:0 auto;}
优点:只需要对自身进行设置 ,子元素宽高不固定的情况可以使用
缺点:不兼容IE6和IE7
适用场景:子元素数量多,子元素宽高不固定的情况可以使用,不方便修改父元素的属性,对浏览器版本要求相对较低时使用
*/
.parent3 {
background: red;
height: 200px;
}
.child3 {
color: white;
CSS居中问题大总结
最新推荐文章于 2020-09-01 15:11:07 发布
本文详细总结了CSS实现元素水平垂直居中的多种方法,包括使用Flexbox、Grid布局、传统方法等,深入探讨每种方法的适用场景及优缺点,帮助开发者更好地理解和应用CSS居中技巧。
摘要由CSDN通过智能技术生成