CSS实现垂直居中的7种方法

html-css09

CSS实现垂直居中的7种方法,第1张

HTML:

CSS:

重点:父容器高度和子元素line-height一样的数值,内容中的行内元素就会垂直居中。

HTML:

CSS:

重点:给父元素添加一个伪元素::before,让这个伪元素的div高度为100%,这样其他div就可垂直居中了,但div 本身就是块级元素,而vertical-align是行内元素属性,则需要修改为inline-block。

HTML:

CSS:

重点:在父元素中设置相对定位position: relative,子元素设置绝对定位 position: absolute;top和left相对父元素的50%,与其搭配的 transformse: translate(-50% , -50%)表示X轴和Y轴方向水平居中。

HTML:

CSS:

重点:子元素绝对定位position:absolute,父元素相对定位position: relative,将上下左右的数值都设置为0,同时margin:auto。绝对定位是会脱离文档流的,这点要注意一下。

HTML:

CSS:

重点:给父元素设置display: flex布局,水平居中 justify-content: center,垂直居中align-items: center。

HTML:

CSS:

重点:父元素position定位为relative,子元素position定位为absolute。水平居中同理。calc居中要减多少要结合到自己的宽高设置多少再进行计算。

HTML:

CSS:

重点:将父元素设置display:table,子元素table-cell会自动撑满父元素。组合 display: table-cell、vertical-align: middle、text-align: center完成水平垂直居中。

如下:

1、line-height属性使文字垂直居中。

2、使用绝对定位和负外边距对块级元素进行垂直居中(已知元素的高度)。

3、使用绝对定位和transform进行垂直居中(未知元素高度)。

4、使用flex布局。

介绍

层叠样式表(英文全称:Cascading Style Sheets)是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。CSS不仅可以静态地修饰网页,还可以配合各种脚本语言动态地对网页各元素进行格式化。

CSS能够对网页中元素位置的排版进行像素级精确控制,支持几乎所有的字体字号样式,拥有对网页对象和模型样式编辑的能力。

1.首先,打开HTML编辑器并创建一个新的HTML文件,比如index。说明:html,用于填写代码的基本层次的问题。-

2.在index.html中的<style>标签中,将“.shoucang .sc_ul li”中的“height: 73px”调整为:height: 73pxpadding-top: 7px。

3.最后,浏览器运行index.html页面,发现li标记中的文本垂直和水平居中。

扩展资料:

其他代码:

Thecodeisasfollows:

<style type = "text/CSS" >

.Shoucang{

Width:58px;

Height:300px;

Float:correct;

Background-color:#CCC;

Border:1pxentity#999;

.Shoucang.Sc_ul{

Width:21px;

Margin-right:car;

Margin-left:car;

Thelist-style-type:no;

Padding-top:20px;

Padding-right:0px;

Padding-bottom:0px;

Padding-left:0px;

Margin-top:0px;

Margin-bottom:0px;

.Shoucang.Sc_ulli{

Thetext-align:center;

Vertical-align:intermediate;

Height:80px;

Width:21px;

Margin-bottom:9px;

Color:#FFF.

Textmodification:no;

Thetext-align:center;

Vertical-align:intermediate;

Background-color:#FF0000;

Fontsize:12px;

Border:1pxentity#666;

-->

></ style

</ a >

The <body >

<div class = "shoucang" >

<ul class = "sc_ul" ><li >set as home </ li ><li >lee </ >

<li class = "no" >contact way lee </ a >

</ ul >