前端的那些居中方法

您所在的位置:网站首页 前端页面显示数据怎么设置 前端的那些居中方法

前端的那些居中方法

2024-07-11 19:34| 来源: 网络整理| 查看: 265

文章目录 一,最常用简单二,几种定位(position)的居中方法三,其他百分比布局中的居中其他表格内容居中盒子水平和垂直居中

水平居中:左右两边的间距是一样的垂直居中:上边和下边的间距是一样的 一,最常用简单 div页面居中,实例如下(盒子居中最优法) width: 600px; height: 400px; top: 50%; left: 50%; margin-left: -300px; margin-top: -200px; div中的文字水平居中:text-align:center; (文本居中多用)div中的文字垂直居中:line-height:值;

div其他文本对齐

文本居中对齐:.. 居右对齐:.. 居左对齐:.. 两端对齐:.. 二,几种定位(position)的居中方法

1,因为relative相对定位的元素在正常的文档流中,所以使用margin-left和margin-right为auto就可以实现水平居中了,不过要记得设置宽度。也可以用 left : 0 ; right : 0 ; margin : auto ;代替。

position: relative; background-color: green; width: 50px; margin:0 auto;

2,absolute需要设置更多的属性来实现居中,如: 方法一:使用left、right、margin值为0,实现水平居中,使用top、bottom、margin值为0实现垂直方向上居中,可以分开使用,也可以组合起来使用。同时,也需要设置宽度。

position: absolute; left: 0; right: 0;top: 0;bottom: 0; margin: auto; width:25px; height:25px; background:red;

同时,如果把上面代码中的position设置为relative,则只能实现水平居中,而无法垂直方向上居中。

方法二:这种方法也可以实现水平垂直方向上都居中,但要兼容。不需要设置宽度,可以根据内容变化。

position: absolute; background: red; top: 50%; left: 50%; transform: translate(-50%, -50%);

方法三:可以用left:50%加上margin-left:-(宽度/2),来实现绝对定位的水平居中,注意:这里的宽度指的是设置为绝对定位的元素的宽度。

position: absolute; background: red; left:50%; margin-left:-24%; width:48%; 三,其他百分比布局中的居中

垂直&水平居中的几种方法 :

1.以em/rem设置宽度和高度 父级设置 width:5rem; height:5rem; text-align:center; 子集设置 line-height:5rem;

2.利用trunsform 父级设置 width:5rem; height:5rem; position:relative 子集设置 position:absolute; top:50%;left50%;transform:translate(-50%,-50%);

3.高版本浏览器 父级设置 display-flex; justify-content:center; align-items:center;

4.子集为inline-block则 父级设置 text-align:center

其他 表格内容居中 数学

col 元素为表格中的三个列规定了不同的对齐方式:

两个 colgroup 元素为表格中的三列规定了不同的对齐方式和样式 (注意第一个 colgroup 元素横跨两列):

在这里插入图片描述

注意:text-align不可以对行内元素居中 盒子水平和垂直居中

在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3