<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="index01.css"> <title>居中布局的几个实现方案</title> </head> <body> <div class="left"></div> <div class="right">DEMO</div> </body> </html>
标签结构很简单,就是一个父元素里面套了一个子元素css
想要实现左右布局,只须要把<div class="left"></div>
设置成向左浮动,右边向右浮动html
.left{ float: left; } .right{ float: right; }
或者把left和right设置成inline-block布局
.left{ display: inline-block } .right{ display: inline-block }
html
结构<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="index01.css"> <title>居中布局的几个实现方案</title> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
标签结构很简单,就是一个父元素里面套了一个子元素flex
text-align
和inline-block
实现text-align
只针对inline
元素有效,所以,能够在父元素设置text-align:center
,而后改变子元素display:block
为inline-block
.index01.css
的代码为:.parent{ height: 200px; background-color: gray; text-align: center; } .child{ background-color: yellowgreen; height: 200px; width: 200px; display: inline-block; }
display:table
和margin:0 auto
实现margin:0 auto
实现水平居中display:table
这个元素的做用就像 <table>
元素. 它定义了一个块级盒子.index02.css的代码为;spa
.parent{ height: 200px; background-color: gray; } /*display:table 在表现形式上很像是block元素 宽度跟着内容走。 */ .child{ display: table; margin: 0 auto; background-color: greenyellow; height: 200px; width: 200px; text-align: center; line-height: 200px; }
position:absolute
和left: 50%
以及transform: translateX(-50%)
实现position: relative
left:50%
则能够根据左边进行定位transform
,则能够根据自身的宽度偏移index03.css的代码为:code
.parent{ height: 200px; background-color: gray; position: relative; } .child{ position: absolute; left: 50%; transform: translateX(-50%); height: 200px; background-color: greenyellow; }
flex
+justify-content
实现display:flex
,则第一级子元素是flex-item
justify-content: center;
就能够实现居中/////////orm
margin:0 auto
实现居中index04.css的代码为:htm
.parent{ height: 200px; background-color: gray; display: flex; justify-content: center; } .child{ height: 200px; background-color: greenyellow; /* margin: 0 auto; */ }
左中右布局参考一的左右布局,可将三个元素都设置成float:left
或者将三个元素都设置成dispaly:inline-block
it
4、垂直居中io
height
和line-height
设置垂直居中display:flex和
align-items: center`