在样式设计中,我们会经常遇到居中问题,普通盒子对齐,可以用margin: auto
来解决,比较方便。
但当一个父盒子下面有两个子元素,令其中一个子元素居中就不太方便
<head>
<meta charset="utf-8">
<title></title>
<style>
.box1 {
width: 200px;
height: 200px;
background-color: skyblue;
margin: 100px auto;
}
.box2 {
width: 100px;
height: 100px;
margin: auto;
background-color: red;
}
</style>
</head>
<body>
<div class="box1">
<span>123</span>
<div class="box2"></div>
</div>
</body>
运行结果如下:
可以看到,虽然box2相对于box1水平居中了,但无法置顶居中,因为box2会受到
<span>123</span>
的排版影响。如果想让box2自由的居中对齐,应该想到用绝对定位使其脱离标准流
下面是利用定位来解决的代码:
<head>
<meta charset="utf-8">
<title></title>
<style>
.box1 {
position: relative;
width: 200px;
height: 200px;
background-color: skyblue;
margin: 100px auto;
}
.box2 {
position: absolute;
/* 先将box2移动到 左边框离父盒子左边框的距离为
父盒子宽的50% */
left: 50%;
top: 0;
/* 然后往右移动box2宽度的一半, */
margin-left: -50px;
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="box1">
<span>123</span>
<div class="box2"></div>
</div>
</body>
运行结果:
同理还可以将box2靠右垂直居中对齐
只需要改动以下代码:
top: 50%;
right: 0;
margin-top: -50px;
运行结果如下:
本人前端初学菜鸟,大家有更好的建议或方法欢迎指出。