分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 运营维护

纯CSS-元素水平垂直居中之fit-content布局

发布时间:2023-09-06 01:36责任编辑:傅花花关键词:CSS

实现一个元素水平垂直居中的方法很多:

  • 元素未知宽高

width和height的fit-content值只支持Chrome和Firefox浏览器

 1 .box { 2 ????position: absolute; 3 ????top: 0; 4 ????left: 0; 5 ????bottom: 0; 6 ????right: 0; 7 ????margin: auto; 8 ????width: fit-content; 9 ????width: -webkit-fit-content;10 ????width: -moz-fit-content;11 ????height: fit-content;12 ????height: -webkit-fit-content;13 ????height: -moz-fit-content;14 ????overflow: hidden;15 ????text-align: center;16 ????background-color: #eee;17 }
  • 元素已知宽高

大家对这个应该是很了解的,也是实际开发中运用最多的,推荐给刚刚入门的小伙伴吧。

设置它的父元素为position:relative即可:

第一种方式:

 1 .children{ 2 ????position: absolute; 3 ????top: 0; 4 ????bottom: 0; 5 ????left: 0; 6 ????right: 0; 7 ????margin: auto; 8 ????width: 300px; 9 ????height: 200px;10 ????background-color: #5f9a3f;11 }

第二种方式:

1 .children{2 ????position: absolute;3 ????top: 50%;4 ????left: 50%;5 ????margin: -100px 0 0 -150px;6 ????width: 300px;7 ????height: 200px;8 ????background-color: #5f9a3f;9 }

第三种方式:

使用CSS3新属性transform的translate属性

1 .children{2 ????position: absolute;3 ????top: 50%;4 ????left: 50%;5 ????transform: translate(-50%,-50%);6 ????width: 300px;7 ????height: 200px;8 ????background-color: #5f9a3f;9 }

感谢阅读,欢迎大家来吐糟。

纯CSS-元素水平垂直居中之fit-content布局

原文地址:https://www.cnblogs.com/belongto/p/8295364.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved