html css 实现元素的水平居中、垂直居中 全面 方法

一.水平居中 

------------------------------------------------------------------------------

在html中,元素主要分为行内元素和块级元素;

行内元素指的是书写完成后不会自动换行,并且元素没有宽和高。

块级元素写完后会自动换行,有宽高可以修改。

还有一种特殊的元素叫做行内块元素。

大致分内是:

行内元素有:heda   meat   title  lable  span  br  a   style  em  b  i   strong

块级元素有:body  from  select  textarea  h1-h6 html table  button  hr  p  ol  ul  dl  cnter  div

行内块元素常见的有: img  input  td  

扫描二维码关注公众号,回复: 2423688 查看本文章
------------------------------------------------------------------------------


测试的html代码

< div class= "box" >
< a class= "blog" href= "" >追求者的博客 blog.csdn.net/example440982 </ a >
< div class= "blog2" >追求者的博客 blog.csdn.net/example440982 </ div >
< p >追求者的博客 blog.csdn.net/example440982 </ p >
< img src= "text.png" width= "50" height= "50" >
</ div >


css样式

(1)行内元素解决方案

只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可:

 
.box {
text-align: center;
}

(2)块状元素解决方案

 
.box {
width: 200px; /*要设置宽度才有效*/
margin: 0 auto;
}

(3)多个块状元素解决方案
将元素的display属性设置为inline-block,并且把父元素的text-align属性设置为center即可:

 
.box {
text-align: center;
}
.child {
display: inline-block;
}

(4)多个块状元素解决方案 (使用flexbox布局实现)
使用flexbox布局,只需要把待处理的块状元素的父元素添加属性display:flex及justify-content:center即可:

 
.level-center {
display: flex;
justify-content: center;
}

二.垂直居中

(1)单行的行内元素解决方案  a标签垂直居中

.box {
background: #ccc;
height: 240px;
}
.box a {
line-height: 240px;
}

(2)多行的行内元素解决方案
组合使用display:table-cell和vertical-align:middle属性来定义需要居中的元素的父容器元素生成效果,如下:

.box {
background: #ccc;
width: 300px;
height: 300px;
/*使元素垂直居中*/
display: table-cell;
vertical-align: middle;
}

(3)已知高度的块状元素解决方案

 
.box {
position: relative;
width: 300px;
height: 300px;
background: pink;
}
.blog2 {
position: absolute;
height: 100px;
background: #ccc;
top: 50%;
margin-top: -50px; /*设置边距为自身高度的一半*/
padding: 0;
}


三.水平垂直居中


(1)已知高度和宽度的元素解决方案1
这是一种不常见的居中方法,可自适应,比方案2更智能,如下:

.blog2 {
position: absolute;
width: 300px;
height: 200px;
background: #ccc;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}

(2)已知高度和宽度的元素解决方案2

.blog2 {
position: absolute;
width: 300px;
height: 200px;
background: #ccc;
top: 50%;
left: 50%;
margin-top: -100px; /*盒子自身高度的一半*/
margin-left: -150px; /*盒子自身宽度的一半*/
}

(3)未知高度和宽度元素解决方案

.blog2 {
position: absolute;
/* width: 300px;
height: 200px; */
background: #ccc;
top: 50%;
left: 50%;
transform: translate( -50%, -50%);
}

(4)使用flex布局实现

.box {
display: flex;
justify-content: center;
align-items: center;
background: #ccc;
height: 200px;
}

猜你喜欢

转载自blog.csdn.net/example440982/article/details/80489037