居中:
块级元素中的行内元素居中:块级元素设置text-align:center就可以居中
<div style="text-align:center">
<a href="http://www.baidu.com" titile="百度一下,你就知道">搜索</a>
</div>
水平居中:外边距、改变盒模型、定位实现水平居中
外边距:块级元素设置宽度,margin:0 auto
CSS
h2{
width:200px;
margin:0 auto;
}
HTML
<header><h2>你好,我是2号标题</h2></header>
为什么需要给块级元素设置宽度?
不设宽度的情况下,块级元素独占一行(margin元素外边距),因此只设置margin外边距块级元素还是原来的样子。
改变盒模型:
方法一:
1.块级子元素调整为display:inline-block
(默认宽度可以根据内容变化)
2.块级父元素设置对齐方式text-align:center
CSS
header{
text-align:text;
}
h2{
display:inline-block;
}
HTML
<header><h2>你好,我是2号标题</h2></header>
方法二:
1.将盒模型改成display:flex
(伸缩盒模型)
2.justify-content:center;
CSS
.father{
display:flex;
justify-content:center;
}
HTML
<div class="father">
<section class="son">拜拜</section>
</div>
定位:
脱离文档流:
子元素设置position:absolute
;(相对于最近的父级块元素定位属性不为static进行定位,脱离文档流)
父元素设置:position:relative;
(未脱离文档流,根据原来所占位置做偏移,原来所占空间还会保留)
1.父级元素设置display:relative;
2.子元素设置diaplay:absoliute;left:50%;
3.如果子元素设置了宽度,可以设置margin-left:-宽/2
或transform:translateX(-50%)
;没有设置宽度:transform:translateX(-50%)
CSS
.father{
position:realtive;
background-color:blue;
/**避免高度塌陷**/
height:300px;
}
.son{
postion:absolute;
/**往父元素里移50%**/
left:50%;
/**参照自身的宽度再往回移50%**/
transform:translateX(-50%);
}
HTML
<div class="father">
<section class="son">拜拜</section>
</div>
注:如果不给父元素设置定位属性,绝对定位的子元素会一直往上搜索由定位属性的元素,直到找到body,此时定位就相对于整个body。再相对于页面水平居中的时候,可以直接设置
position:absolute;
left:50%;
transform:translateX(-50%);
就可以相对于页面水平居中了。
相对于页面水平居中,也可以:
postion:fixed;
left:50%;
transform:translatX(-50%);
垂直居中:
通过设置行高、内外边距、改变盒模型、定位方式
设置行高:
容器height已知,单行文本,line-heigh=height
CSS
.container{
height:50px;
line-height:50px;
/**下面内容方便看效果**/
background-color:red;
color:#fff;
}
HTML
<div class="container">
<span class="txt">拜拜!</span>
</div>
注:如果单行文本内容是图片,设置line-height不会垂直居中,图片底端是相对于文本的基线对齐。设置line-height对图片不起作用。
设置内边距
上下内边距相同,内容垂直居中
.container{
padding:50px 0;
}
注:如果给class="container"div
元素设置高度,默认元素盒模型box-sizing
是content-box(标准盒模型)
,此时div元素
的高度大于内容的高度,设置padding
的上下边距,不会处置居中,上图
改变盒模型:
方法一:
1.display:flex;
2.align-items:center;
CSS
.container{
display:flex;
align-items:center;
}
HTML
<div class="container">
<span class="txt">拜拜!</span>
</div>
方法二:
1.父元素设置display:table
2.子元素设置:display:table-cell;vertical--align:center
其中vertical-align
属性用于行内元素盒表格单元格
table-cell
相当于td
;display:table拥有块级元素的特点。
CSS
.container{
display:table;
}
.txt{
display:table-cell;
vertical-align:middle;
}
HTML
<div class="container">
<span class="txt">拜拜!</span>
</div>
注:使用table盒类型,渲染效果不会独占一行。但是flex盒类型,渲染效果会独占一行。
定位:
脱离文档流
父元素设置position:relative;
子元素设置position:absolute,top:50%;
子元素向上偏移 transform:translateX(-50%)
或者margin-top:-高/2
(设置高的情况下);
CSS
.father{
position:relative;
height:300px;
background-color:blue;
width:300px;
}
.son{
position:absolute;
top:50%;
transform:translateY(-50%);
background-color:red;
}
HTML
<div class="father">
<section class="son">拜拜</section>
</div>