分享web开发知识

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

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

CSS垂直居中布局问题

发布时间:2023-09-06 01:48责任编辑:彭小芳关键词:CSS

最近总被这玩意坑,面试官也老爱问,“还有别的方式吗”.......

1、使用绝对定位

元素在过度受限情况下,将margin设置为auto,浏览器会重算margin的值,过度受限指的是同时设置top/bottom与height或者left/right与width

有点需要注意的是,设置子元素的宽度高度。

1 ????<div class="container">2 ????????<div class="center absolute_center"></div>3 ????</div>
HTML

CSS:

 1 <style type="text/css"> 2 ????????.absolute_center{ 3 ????????????position:absolute; 4 ????????????width:200px; 5 ????????????height:200px; 6 ????????????top:0; 7 ????????????bottom:0; 8 ????????????left:0; 9 ????????????right:0;10 ????????????margin:auto;11 ????????????background:#333;12 ????????????resize:both;/*用于设置了所有除overflow为visible的元素*/13 ????????????overflow:auto;14 ????????}15 </style>

2、文字简单居中

使用lineheight实现简单的垂直居中

1 <div class="single_line">2 ??????文字文字文字文字文字文字文字TextTextTextTextTextText3 </div>

CSS:

1 ??<style type="text/css">2 ????.single_line{3 ??????height: 30px;4 ??????font-size: 14px;5 ??????line-height: 30px;6 ??????text-align: center;7 ??????border: 1px solid #518dca;8 ????}9 ??</style>

3、使用Flex弹性盒子

Flex在移动端的布局中非常常见,但是对低版本的浏览器有兼容性问题。

父容器container需要设置height高度

1 <div class="container">2 ????????????<div class="center">3 ????????????CENTER ???????????????4 ????????????</div>5 ????</div>
 1 ????????.container{ 2 ??????????height: 500px; 3 ??????????background: #333333; 4 ??????????display: flex; 5 ??????????justify-content: center; 6 ??????????align-items: center; 7 ????????} 8 ????????.center{ 9 ????????????width: 100px;10 ????????????height: 100px;11 ????????????background-color: #fff;12 ????????}

4、使用transform属性位置偏移

父容器需要设置height

1 ????<div class="container">2 ????????<div class= "center">center</div>3 ????</div>
 1 ????<style type="text/css"> 2 ????????.container{ 3 ????????????height:300px; 4 ????????????background:#d6d6d6; 5 ????????????position:relative; 6 ????????} 7 ????????.center{ 8 ????????????position: absolute; 9 ??????????????top: 50%;10 ??????????????left: 50%;11 ??????????????transform: translate(-50%, -50%);12 ????????????13 ????????????width:100px;14 ????????????height:100px;15 ????????????background-color:#666;16 ????????}17 ????</style>

5、使用table-cell布局

父容器需要设置height、width的值

1 ????<div class="container">2 ????????<span class="center">center</span>3 ????</div>
 1 ????<style type="text/css"> ????2 ????????.container{ 3 ????????????width:500px; 4 ????????????height:500px; 5 ????????????background:#d6d6d6; 6 ????????????display:table-cell; 7 ????????????text-align:center; 8 ??????????vertical-align:middle; 9 ????????}10 11 ????????.center{12 ????????????background-color:#666;13 ????????}14 ????</style>

CSS垂直居中布局问题

原文地址:https://www.cnblogs.com/synchronize/p/8724615.html

知识推荐

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