分享web开发知识

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

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

css布局--垂直水平居中

发布时间:2023-09-06 02:01责任编辑:沈小雨关键词:暂无标签

最近在总结前端知识,也参加了一些面试,面试中遇到一道题要求垂直水平居,现在对这进行一下总结,也好巩固一下知识。

方案一、flex布局

 .layout.flex{ ???????????display: flex; ???????????width:100%; ???????????align-items: center; ???/*在交叉轴上如何对齐*/ ???????????justify-content: center; ????/*在主轴上如何对齐*/ ???????????height: 300px; ???????????border: 1px solid #000000; ???????}<section class="layout flex"> ???<h1>flex布局水平垂直居中方案</h1></section>

  方案二、margin:auto

#content{ ???????????position: absolute; ???????????margin: auto; ???????????top:0; ???????????bottom: 0; ???????????left: 0; ???????????right: 0; ???????????width: 300px; ???????????height: 100px; ???????????border: 1px solid blue; ???????????/*将section中的文字也水平垂直居中*/ ???????????text-align: center; ???????????line-height: 100px; ???????} ???</style> <section id="content"> ???????水平垂直居中--margin:auto ???</section>

  这里的section设置任意的高度和宽度都可以实现水平垂直居中的效果。

方案三、transform

 #content{ ???????????position: absolute; ???????????top:50%; ???????????left: 50%; ???????????height: 100px; ???????????width: 500px; ???????????border: 1px solid blue; ???????????transform: translate(-50%, -50%); ???????} <section id="content"> ???????垂直水平居中--translate ???</section>

  使用transform方式可居中任意宽高的元素,缺点是transform只有IE10+以及其他现代浏览器才支持,存在兼容性问题。

方案四、表格布局

 ?.container{ ???????????width: 60%; ???????????height: 300px; ???????????border: 1px #000000; ???????????display: table; ???????} ???????.cell{ ???????????display: table-cell; ???????????text-align: center; ???????????vertical-align: middle; ???????????border: 1px solid blue; ???????}<section class="container"> ???????<div class="cell">水平垂直居中--table</div> ???</section>

  表格布局方式兼容性较好

css布局--垂直水平居中

原文地址:https://www.cnblogs.com/jingmi-coding/p/9218863.html

知识推荐

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