
在上面的图像中,有一个红色的div,宽度为100%,高度未知。高度由橙色div的高度控制,可能还会加上一些填充。
橙色div的高度和宽度由动态文本内容控制,我们事先不知道这些内容,但橙色div应该在红色div中水平居中,两侧宽度相等。
蓝色div的宽度和高度是固定的(比方说50px x 50px,比橙色div小),放在左边。它有时是可见的,有时是不可见的(由javascript控制-无论是可见性还是显示,无论哪个效果最好),但在任何一种情况下,它都不应该影响橙色div的水平居中。但是,蓝色div的垂直中心应该垂直对齐,以匹配橙色div的垂直中心。
我可以添加额外的div,或者更改为跨度,任何类似的东西,但目前我尝试的任何东西都意味着,当我需要蓝色div时,橙色div的水平居中的流将考虑到蓝色div,而我需要将蓝色div完全去掉。
有什么想法吗?
发布于 2017-08-17 22:09:20
你应该使用display: flex和align-items,给你的容器传递一个min-height也很重要。
我已经创建了一个快速小提琴来解释我从您那里理解的内容。
看看这个(JSFiddle):
.container {
width: 300px;
padding-bottom: 20px;
padding-top: 20px;
border: solid 1px red;
display: flex;
align-items: center;
justify-content: center;
min-height: 30px;
}
.inner {
background: rgba(0, 0, 0, 0.5);
width: 50%;
}
.fixed {
position: fixed;
left: 20px;
border: solid 1px blue;
height: 30px;
}<div class="container">
<div class="inner">
Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum Lorem Ipsum Lorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem IpsumLorem Ipsum
</div>
<div class="fixed">
fixed
</div>
</div>
发布于 2017-08-17 22:14:14
绝对定位蓝色div,并使用transform将其居中。您需要在两个彩色div周围添加一个容器。
.red {
border: 2px solid red;
width: 100%;
}
.container {
position: relative;
}
.blue {
background-color: blue;
border: 2px solid darkblue;
width: 70px;
height: 70px;
position: absolute;
left: 40px;
top: 50%;
transform: translate(0, -50%);
}
.yellow {
background-color: yellow;
border: 2px solid goldenrod;
margin: 10px auto 50px;
width: 120px;
height: 200px; /* change me */
}<div class="red">
<div class="container">
<div class="blue">
</div>
<div class="yellow">
</div>
</div>
</div>
https://stackoverflow.com/questions/45737208
复制相似问题