CSS/CSS3 实现 居中(水平&垂直)

栏目: CSS · 发布时间: 6年前

内容简介:把行内元素放在一个属性块(display:block)元素中,然后设置父层元素属性居中:.test {}

1,水平居中:行内元素

把行内元素放在一个属性块(display:block)元素中,然后设置父层元素属性居中:

.test {

text-align:center;

}

2,水平居中:块状元素

设置外边距

.test {

margin: 100px auto;

}

3,水平居中:多个块状元素

把块状元素属性(display:inline-block),然后设置父层元素属性居中:

.test {

text-align:center;

}

4,水平居中:多个块状元素(flexbox布局实现)

把块状元素的父元素属性 display:flex和justify-content:center,如下设置:

.test {

text-align:center;

}

5,垂直居中:单行的行内元素

设置height和line-height属性

.test {

height: 100px;
line-height:100px;

}

6,垂直居中:多行的行内元素

给要居中的父元素设置display:table-cell和vertical-align:middle属性

.test {

background: red;
width: 200px;
height: 200px;
/* 以下属性垂直居中 */
display: table-cell;
vertical-align:middle;

}

7,垂直居中:已知高度的块状元素

给要居中的元素设置如下属性

.test {

top: 50%;
margin-top: -50px;  /* margin-top值为自身高度的一半 */
position: absolute;
padding:0;

}

8,水平垂直居中:已知高度和宽度的元素

给要居中的元素设置如下属性

(1)

.test {

position: absolute;
margin:auto;
left:0;
top:0;
right:0;
bottom:0;

}

(2)

.test{

position: absolute;
top: 50%;
left: 50%;
margin-top: -75px;  /* 设置margin-left / margin-top 为自身高度的一半 */
margin-left: -75px;

}

9,水平垂直居中:未知高度和宽度元素

给要居中的元素设置如下属性

.test {

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);  /* 使用css3的transform来实现 */

}

10,水平垂直居中:可用flex

设置如下属性

.test {

display: flex;
justify-content:center;
align-items: center;
/* 注意这里需要设置高度来查看垂直居中效果 */
background: #AAA;
height: 300px;

}


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Dynamic Programming

Dynamic Programming

Richard Bellman / Dover Publications / 2003-03-04 / USD 19.95

An introduction to the mathematical theory of multistage decision processes, this text takes a "functional equation" approach to the discovery of optimum policies. The text examines existence and uniq......一起来看看 《Dynamic Programming》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具