<div class="x1">
<div class="x2">
</div>
</div>
如何让x2垂直于x1?可以自适应的那种
谢谢
.x1{width:500px;height: 500px; border:1px solid #333;position: relative;}
.x2{position:absolute; top:50%; transform:translate(0,-50%); width:100px;height: 100px;background: #333; }
.x1{display: table-cell; vertical-align: middle;height: 800px;border:1px solid #333;}
.x2{ width:100px; height: 100px; background: #f00;}
可以设置 div
为绝对定位,然后定义 margin
为 auto
,top
left
right
bottom
都为 0
,它上也不行,下也不行,左也不行,右也不行,只能乖乖水平垂直都居中了,哈哈哈哈哈。
用 flexbox
的特性可以很簡單就實現垂直居中和自適應:
<div class="parent">
<div class="child"></div>
</div>
.parent {
display: flex;
width: 100%;
height: 300px;
background: #cecece;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
.child {
background: #000;
width: 10%;
height: 10%;
}
實現
jsFiddle
.wrap {
width: 1000px;
height: 1000px;
position: relative;
background: #000;
}
.box {
width: 450px;
height: 450px;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
background: #fff;
}
.x1{
height:500px;
position:relative;
background-color:pink;
width:600px;
}
.x2{
width:100px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin-top:-100px;
margin-left:-50px;
background-color:yellow;
}
x1的宽度和高度随便变化x2都会居中