使盒子水平居中的方法有哪些
flex布局
<style>
* {
margin: 0px;
padding: 0px;
list-style: none;
}
ul {
display: flex;
width: 400px;
height: 400px;
background-color: pink;
justify-content: center;
/* align-items: center; */ /* 控制垂直居中 */
}
li {
width: 200px;
height: 200px;
background-color: green;
}
</style>
</head>
<body>
<ul>
<li>盒子</li>
</ul>
</body>
margin:auto 方法
<style>
* {
margin: 0px;
padding: 0px;
list-style: none;
}
ul {
display: flex;
width: 400px;
height: 400px;
background-color: pink;
}
li {
width: 200px;
height: 200px;
background-color: green;
margin: 0 auto;
}
</style>
</head>
<body>
<ul>
<li>盒子</li>
</ul>
</body>
transform 方法
<style>
* {
margin: 0px;
padding: 0px;
list-style: none;
}
ul {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
li {
position: absolute;
left: 50%;
/* top: 50%; */ /* 控制垂直居中 */
width: 200px;
height: 200px;
background-color: green;
transform: translate(-50%, 0);
}
</style>
</head>
<body>
<ul>
<li>盒子</li>
</ul>
</body>
margin :间距方法
<style>
* {
margin: 0px;
padding: 0px;
list-style: none;
}
ul {
position: relative;
width: 400px;
height: 400px;
background-color: pink;
}
li {
position: absolute;
width: 200px;
height: 200px;
background-color: green;
margin-left: 100px;
/* margin-top: 100px; */ /* 控制垂直居中 */
}
</style>
</head>
<body>
<ul>
<li>盒子</li>
</ul>
</body>
所有代码出图都是一样的
ps:如有其他的方法,欢迎指出