Skip to content

1.左右居中

    1. flex 布局 justify-content 属性
css
.container {
  display: flex;
  justify-content: center;
}
.container {
  display: flex;
  justify-content: center;
}
  1. center 标签
html
<center>
    被居中的元素
    ...
</center>
<center>
    被居中的元素
    ...
</center>
  1. text-align 属性
css
.container {
  text-align: center;
}
.container {
  text-align: center;
}

2.上下居中

flex 布局 align-items 属性

css
.container {
  display: flex;
  align-items: center;
}
.container {
  display: flex;
  align-items: center;
}

3.上下左右居中

  • flex实现上下左右居中
css
.flex-container {
  height:100px;
  width:100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex-container {
  height:100px;
  width:100px;
  display: flex;
  justify-content: center;
  align-items: center;
}
  • grid实现上下左右居中
html
<div class="parent">
	<div class="box" contenteditable="">居中子元素</div>
</div>
<div class="parent">
	<div class="box" contenteditable="">居中子元素</div>
</div>
css
.parent {
	background-color: skyblue;
	width: 400px;
	height: 400px;
	display: grid;
	place-items: center;
	}
.box {
	width: 100px;
	height: 100px;
	background-color: antiquewhite;
	}
.parent {
	background-color: skyblue;
	width: 400px;
	height: 400px;
	display: grid;
	place-items: center;
	}
.box {
	width: 100px;
	height: 100px;
	background-color: antiquewhite;
	}

4.竖着一排剧中

  • flex布局
css
.flex-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.flex-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

5.横着一排剧中

  • flex布局
css
.container {
  display: flex;
  align-items: center;
}
.container {
  display: flex;
  align-items: center;
}

absolute元素居中

html
<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<title>练习的地方</title>
	<style>
	.main {
		position: absolute;
		width: 700px;
		height: 500px;
		background: pink;
		left: 50%;    //起始是在body中,横向距左50%的位置
		top:50%;      //起始是在body中,纵向距上50%的位置,这个点相当于body的中心点,div的左上角的定位
		transform:translate(-50%,-50%);//水平、垂直都居中,也可以写成下面的方式
        /*margin-left:-350px;
        margin-top:-250px;*/
	}
</style>
</head>
<body>
	<div class="main">第1个固定</div>
</body>
</html>
<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<title>练习的地方</title>
	<style>
	.main {
		position: absolute;
		width: 700px;
		height: 500px;
		background: pink;
		left: 50%;    //起始是在body中,横向距左50%的位置
		top:50%;      //起始是在body中,纵向距上50%的位置,这个点相当于body的中心点,div的左上角的定位
		transform:translate(-50%,-50%);//水平、垂直都居中,也可以写成下面的方式
        /*margin-left:-350px;
        margin-top:-250px;*/
	}
</style>
</head>
<body>
	<div class="main">第1个固定</div>
</body>
</html>