首页 > 编程知识 正文

css水平垂直居中的方法,css垂直水平居中方式

时间:2023-05-05 09:06:24 阅读:185856 作者:4239

说明:这篇文章只是总结了几种方法,不说明例子中使用的各要素的属性。 有关详细信息,请参阅MDN文档。 非常详细。 例子在chrome浏览器下完全容易使用,是一个叫IE的废物

附上链接: https://developer.Mozilla.org/zh-cn /

正文中出现的错误,请及时指出留胡子的电灯胆。 人除了圣贤以外什么都是无辜的。 如果有更好的方法,也请留言。 我马上追加。 哈哈!

1、元素水平居中

当然最好的是:

边距: 0自动; 为什么很难居中:

1、元素没有设宽,没有宽怎么会在中间呢!

2、设定了宽度还很难使用。 设定行内要素吧。 关于行内要素和块要素的区别以及如何将行内要素转换为块要素,请参阅我的另一篇文章。

示例1 :

divclass=' box ' divclass=' content '哇! 中心/div/divstyletype=' text/CSS '.box { background-color : # ff8c 00; width: 300px; height: 300px; 边距: 0自动; }.content { background-color : # f00; width: 100px; height: 100px; line-height: 100px; //字符位于块内的垂直中央,文本对齐:中心; //字符中央为margin: 0 auto; (}/style

2、元素水平垂直居中

方案1:position 元素已知宽度

父元素是位置:关系;

子元素是位置: absolute;

根据上50%、左50%,可以通过减去元素自身宽度的距离来实现

示例2 :

divclass=' box ' divclass=' content '/div/div.box { background-color : # ff8c 00; width: 300px; height: 300px; 定位:关系; }.content { background-color : # f00; width: 100px; height: 100px; 定位:助手; left: 50%; top: 50%; margin: -50px 0 0 -50px; }

方案2:position transform 元素未知宽度

不知道元素宽度时,使用上述例子的margin: -50px 0 0 -50px; 替换为:transform: translate(-50%,-50%);

效果就是这样!

示例3 :

divclass=' box ' divclass=' content '/div/div.box { background-color : # ff8c 00; width: 300px; height: 300px; 定位:关系; }.content { background-color : # f00; width: 100px; height: 100px; 定位:助手; left: 50%; top: 50%; transform:translate(-50%、-50%; }

方案3:flex布局

示例4 :

divclass=' box ' divclass=' content '/div/div.box { background-color : # ff8c 00; width: 300px; height: 300px; display :闪存; //flex布局justify-content: center; //对齐子项目的水平中心; //垂直居中子项目}.content { background-color : # f00; width: 100px; height: 100px; }

方案4:table-cell布局

示例5 :

table-cell相当于表的td,因为td是内嵌元素,无法设置宽度和高度,所以嵌套层必须设置display: inline-block; td的背景被橙色覆盖,不推荐

divclass=' box ' divclass=' content ' divclass=' inner '/div/div.box { background-color 3360 # ff8c 00; //橙色width: 300px; height: 300px; 显示:表; }.content { background-color : # f00; //红色display: table-cell; vertical-align :中间; //子元素垂直居中文本对齐:中心; //水平居中子元素}.inner { background-color : # 000; //黑色显示: inline-block; width: 20%; height: 20%; }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。