分享web开发知识

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

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

css实现水平垂直居中方法总结

发布时间:2023-09-06 02:19责任编辑:熊小新关键词:暂无标签

方法一:使用position 元素已知宽度

<div class="box"> ???<div class="content"></div></div><style> ???.box{width:400px; height: 400px;background:red;position: relative;} ???.content{width:150px;height: 100px;background:green; position: absolute;top:200px;left: 200px;margin-left:-75px;margin-top: -50px;}</style>

方法二:position tranform 元素宽度未知

<div class="box"> ???<div class="content"></div></div><style> ???.box{width:400px; height: 400px;background:red;position: relative;} ???.content{width:150px;height: 100px;background:green; position: absolute;top:200px;left: 200px;transform: translate(-50%,-50%);}</style>

得到的效果和上图一样

当使用这种方法将文字放在div水平垂直的位置的时候,会出现字体边缘模糊的结果,解决方法是:使用flex完成垂直居中,设置排列方向为column,并设置justify-content: center,最后用text-align: center完成水平居中。方能保证文字显示清晰。

方法三:felx布局

<style> ???.box{width:400px; height: 400px;background:red;display: flex;justify-content: center;align-items: center;} ???.content{width:150px;height: 100px;background:green;}</style><div class="box"> ???<div class="content"></div></div>

效果和上图一样

方法四:table-cell布局 

因为table-cell相当与表格的td,td为行内元素,无法设置宽和高,所以嵌套一层,嵌套一层必须设置display: inline-block;td的背景覆盖了红色,不推荐使用

<style> ???.box{width:400px; height: 400px;background:red;display: table;} ???.content{background:blue;display: table-cell;vertical-align: middle;text-align:center;} ???.inner{background:green;display: inline-block;width: 150px;height: 100px;}</style><div class="box"> ???<div class="content"> ???<div class="inner"></div> ???</div></div>

css实现水平垂直居中方法总结

原文地址:https://www.cnblogs.com/mexiaoxia/p/9839361.html

知识推荐

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