div盒子水平居中垂直居中的几种方法
来源:互联网 发布:网络鬼故事之603房间 编辑:程序博客网 时间:2024/05/06 14:44
div盒子水平居中垂直居中的几种方法:
一、子盒子固定宽高时:
法一:使用margin: auto;
{
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;position:relative;
}
.box {
width: 400px;height: 200px;background-color: #47c730;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
法二:使用 负margin
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;position:relative;
}
.box {
width: 400px;height: 200px;background-color: #47c730;
position: absolute;
top: 50%;
left: 50%;
margin-left: -200px;
margin-top: -100px;
}
</style>
</head>
<body>
<div class="container">
<div class="box"></div>
</div>
</body>
</html>
二、盒子宽高不固定
法一、使用flex布局,给父元素添加display: flex; justify-content: center;align-items: center;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;
display: flex;
justify-content: center;
align-items: center;
}
.box {
background-color: #47c730;
}
</style>
</head>
<body>
<div class="container">
<div class="box">我没宽度和高度</div>
</div>
</body>
</html>
法二、使用position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.container {
width: 800px;height: 400px;background: #ccc;
position: relative;
}
.box {
background-color: #47c730;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="container">
<div class="box">我没宽度和高度</div>
</div>
</body>
</html>
- div盒子水平居中垂直居中的几种方法
- div盒子水平垂直居中的方法
- div盒子水平垂直居中的方法
- div盒子水平垂直居中的方法
- div盒子在页面中水平垂直居中的几种方法。
- 实现div水平、垂直居中的几种方法
- 让DIV水平和垂直居中的几种方法
- div垂直和水平居中的几种方法
- 水平垂直居中的几种方法
- 水平垂直居中的几种方法
- css 几种水平垂直居中的方法 及 弹性盒子
- div 垂直 居中的几种 方法
- div垂直居中的几种方法
- div水平垂直居中的方法
- 水平垂直居中div三种方法
- div水平居中垂直居中方法
- html中div如何水平和垂直居中的几种css方法代码
- div垂直水平居中的五种方法
- mybatis学习笔记
- 人脸识别解锁
- 更换头像的逻辑代码,两个功能,一个是从图库选择,一个是打开相机自己拍照
- socket阻塞与非阻塞,同步与异步
- 171121之PLSQL安装
- div盒子水平居中垂直居中的几种方法
- 从零开始···AMQ主题模式实现
- 在centos下启动mysqld提示 unrecognized service
- Qt提供通过访问共享内存实现进程间通信
- 线段树的两道模板题 hdu1698 hdu1166
- loadrunner连接数据库
- 类初学
- ubuntu+virtualbox+winn10系统共享文件夹
- Opencv1、Opencv2 拍照片、写视频