我正在尝试将照片设置为50VW(页面宽度的一半),始终仅使用CSS与屏幕左左对齐 - 无需重组HTML。我希望Flexbox的另一半保留在容器内。
本质上,如果您的屏幕宽1600px,则Nick Cage应在左侧0px开始,并延伸至800px(中心),然后.hero-text
应在800px开始,在1400px结束,因为它限于1200px宽度容器。
我已经评论了我认为是关键的一行,但我无法正确完成数学。无论分辨率如何
.container {
width: 100%;
border: 1px solid blue;
height: 500px;
}
.inner {
width: 1200px;
height: 100%;
margin: 0 auto;
border: 1px solid red;
}
.hero {
width: 100%;
height: 100%;
border: 1px solid green;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
text-align: center;
}
.hero > div {
width: 50%;
}
.hero-image {
width: 50vw;
height: 100%;
/* margin-left: calc((100vw - 1200px) * -1); */
background: url('https://www.placecage.com/c/500/400');
background-repeat: no-repeat;
background-size: cover;
}
<div class="container">
<div class="inner">
<div class="hero">
<div class="hero-image">
</div>
<div class="hero-text">Here is Nick Cage, everybody!
</div>
</div>
</div>
</div>
https://jsfiddle.net/cqu6xf90/1/
无需使用任何计算。
使用相对&amp;实现这一目标的绝对定位。请参阅此处以获取其他阅读。https://css-tricks.com/absolute-positioning-inside-relative-position/
您可以将任何子元素"绝对"定位为相对父母。
在这种情况下,将容器元素设置为具有position: relative;
&amp;将英雄图像设置为具有position: absolute; left: 0;
实际上将其设置在元素的左侧。
完整的CSS
.container {
width: 100%;
border: 1px solid blue;
height: 500px;
/* Relative Parent */
position: relative;
}
.inner {
width: 1200px;
height: 100%;
margin: 0 auto;
border: 1px solid red;
}
.hero {
width: 100%;
height: 100%;
border: 1px solid green;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
text-align: center;
}
.hero > div {
width: 50%;
}
.hero-text {
/* Margin to place the text div */
margin-left: 50%;
}
.hero-image {
/* Positions the hero image where you want it */
position: absolute;
left: 0;
width: 50vw;
height: 100%;
/* margin-left: calc((100vw - 1200px) * -1); */
background: url('https://www.placecage.com/c/500/400');
background-repeat: no-repeat;
background-size: cover;
}
查看此codepen http://codepen.io/anon/pen/nbwvmy,以查看其工作。
希望这是您想要的!(当然不弄乱标记)