我想使用relative div
填充inline-block
- 彼此相邻的元素,所有元素都具有相同的宽度和宽度。相同的高度(=正方形)。
因此,如果有n
个元素,relative div
应该在x方向上滚动。这可以在下面的示例代码中看到:
.outer {
position: absolute;
width: 100%;
height: 100%;
}
.parent {
position: relative;
width: 90%;
height: 40%;
overflow-y: hidden;
overflow-x: scroll;
text-align: center;
white-space: nowrap;
background: red;
}
.item {
background: yellow;
display: inline-block;
width: 4%;
margin: 0% 3%;
}
.item::after {
content: "";
display: block;
padding-bottom: 100%;
}
<div class="outer">
<div class="parent">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
但现在我想将item
- 元素(黄色方块)垂直对齐到red parent-div
(相对div)所以从顶部到中心和从底部到中心的距离是相同的。请看这个图片:
注意:我不想更改层次结构(保持父元素相对&amp;外部元素绝对等等...)
我怎样才能做到这一点?
答案 0 :(得分:2)
不使用css flex。
.outer {
position: absolute;
width: 100%;
height: 100%;
}
.parent {
position: relative;
width: 90%;
height: 40%;
overflow-y: hidden;
overflow-x: scroll;
text-align: center;
white-space: nowrap;
background: red;
}
.item {
background: yellow;
display: inline-block;
width: 4%;
margin: 0% 3%;
top: 50%;
transform: translate(-50%, -50%);
position: relative;
}
.item::after {
content: "";
display: block;
padding-bottom: 100%;
}
&#13;
<div class="outer">
<div class="parent">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
&#13;
答案 1 :(得分:0)
我建议使用flexbox
请参阅A Complete Guide to Flexbox。
...定义浏览器如何沿着容器的交叉轴在Flex项目之间和周围分配空间。
.outer {
position: absolute;
width: 100%;
height: 100%;
}
.parent {
position: relative;
width: 90%;
height: 40%;
overflow: hidden;
overflow-x: scroll;
background: red;
display: flex;
align-items: center;
}
.item {
background: yellow;
flex: 0 0 4%;
margin: 0 3%;
}
.item::after {
content: "";
display: block;
padding-bottom: 100%;
}
<div class="outer">
<div class="parent">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
.outer {
position: absolute;
width: 100%;
height: 100%;
}
.parent {
position: relative;
width: 90%;
height: 40%;
overflow-y: hidden;
overflow-x: scroll;
text-align: center;
white-space: nowrap;
background: red;
display: flex;
justify-content:center;
align-items: center;
}
.item {
background: yellow;
flex: 0 0 4%;
margin: 0 3%;
}
.item::after {
content: "";
display: block;
padding-bottom: 100%;
}
<div class="outer">
<div class="parent">
<div class="item"></div>
<div class="item"></div>
</div>
</div>
答案 2 :(得分:0)
只需给.parent元素这个代码,它应该工作: (你可以保留你已经写过的代码)
.parent {
display: flex;
justify-content: center;
align-items: center;
}