[英]Making an image half the page width inside of a smaller container
我正在尝试将照片设置为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://css-tricks.com/absolute-positioning-inside-relative-positioning/
您可以将任何子元素“绝对”定位为相对的父元素。
在这种情况下,将容器元素设置为具有以下position: relative;
并设置英雄形象的position: absolute; left: 0;
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以查看其工作原理。
希望这就是您要寻找的! (当然不要弄乱标记)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.