水平 + 垂直居中

absolute定位:    ** 父级元素不用设置 position:relative ,可以以html为标准水平竖直居中

1)margin-top 和 margin-left 来设置 。必须知道需要居中元素的高度和宽度

.center {
    background-color:red;
    position: absolute;
    height:50px;             //必须设置高度
    width:50px;          //必须设置宽度
    top: 50%;
    left: 50%;
    margin-top:-25px;      //负值,且为高度的一半
    margin-left:-25px;     //负值,且为宽度的一半
}        

 

2)transform 方法不用知道高度的具体值。但是可能存在兼容性问题

.center{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

 

3)margin: auto; 自动适应外边距。这种方法不存在兼容性问题

.center {
    background-color:red;
    position: absolute;
    width:50px;       //必须有宽 高
    height:50px;      //否则会撑满屏幕
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0; 
    margin:auto;
}

 

 

1)父元素设置 flex 属性,需要居中的元素设置外边距auto : display: flex;  +  margin: auto;

.boxFather {
    height: 200px;    //父容器必须有高度
    display:flex;
}

.boxSon {
    margin: auto;    //需要居中的元素设置外边距自适应
}

 

2)flex居中:

.boxFather {
    display: flex;
  justify-content: center;      //水平
  align-items: center;        //垂直
}

 

 


3)grid居中:(网格布局)都可以用
display:grid;
justify-content / justify-items : center        // justify 表示水平  content 表示整个内容区域在容器里面的水平位置      
align-content / align-items : center         // align 表示竖直   items 表示单元格的内容      
place-content / place-items : center center     // place 表示 justify + align ,中间无符号,空格隔开,如果省略第二个值,那么两个值都取第一个



stretch:拉伸,占满单元格的整个宽度(默认值)。
space-around:每个项目两侧的间隔相等。所以,项目之间的间隔比项目与容器边框的间隔大一倍。
space-between - 项目与项目的间隔相等,项目与容器边框之间没有间隔。
space-evenly - 项目与项目的间隔相等,项目与容器边框之间也是同样长度的间隔。


元素居中:align: center;

 

行内元素 水平+竖直居中:1)line-hight 的值等于 hight         // 行高 = 高度

            2)padding: 70px 0;  text-align: center;   // 设置一个上下边距都为70px实现竖直居中,再设置文字水平居中

 

水平居中块级元素:margin: auto;     **该块级元素 width 不能为100%

图片居中也可以用:margin: auto; 

在一个块级元素中,实现水平竖直居中:

文字居中:text-align: center;

 

posted on 2021-03-26 11:40  cropsecrab  阅读(72)  评论(0)    收藏  举报

导航