首先,我们先写一个网页,搭一个基础的布局:
头部高度100px,左侧宽度100px,白色部分为内容区域,宽高不定,随着浏览器大小自适应,现在我们想办法让
这是一个儿子 居中显示
基础布局的代码如下所示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>元素居中</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
}
.bigBox {
width: 100%;
height: 100%;
}
.header {
width: 100%;
height: 100px;
background: green;
}
.container {
display: flex;
height: calc(100% - 100px);
}
.left {
height: 100%;
width: 100px;
background: yellow;
float: left;
}
</style>
</head>
<body>
<div class="bigBox">
<!-- 头部 -->
<div class="header"></div>
<!-- 头部以下区域 -->
<div class="container">
<!-- 左侧 -->
<div class="left"></div>
<!-- 内容区域 -->
<div class="father">
<div class="child">
这是一个儿子
</div>
</div>
</div>
</div>
</body>
<script>
</script>
</html>
1. 父元素宽高不定
1.1 使用calc计算出父元素的宽,使用display给子元素定位;或者使用flex: 1代替宽高计算
.father {
background: pink;
float: left;
display: flex;
/* 垂直居中 */
align-items: center;
/* 横向居中 */
justify-content: center;
/* 方法一:使用flex: 1 */
/* flex: 1; */
/* 方法二:计算宽高 */
width: calc(100% - 100px);
height: 100%;
}
.child {
background-color: red;
}
1.2 使用calc计算出父元素的宽,子元素绝对定位,并使用transform计算子元素移动位置;或者使用flex: 1代替宽高计算
transform的translate() 方法是从当前位置移动元素(根据为 X 轴和 Y 轴指定的参数)
transform:translate(-50%, -50%)
(负数向左移动,负数向上移动)
在style里面加上如下代码:
.father {
background: pink;
float: left;
position: relative;
/* 方法一:使用flex: 1 */
/* flex: 1; */
/* 方法二:计算宽高 */
width: calc(100% - 100px);
height: 100%;
}
.child {
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
效果如图所示:
2. 父元素宽高固定
.father {
background: pink;
float: left;
width:600px;
height: 400px;
display: flex;
align-items: center;
justify-content: center;
}
.child {
background-color: red;
}
或者
.father {
background: pink;
float: left;
position: relative;
width:600px;
height: 400px;
}
.child {
background-color: red;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
效果如图: