daveycroqet daveycroqet - 3 days ago 5
CSS Question

Making an image half the page width inside of a smaller container

I'm trying to set the photo to 50vw (half the page width), always left-aligned with the screen, using only CSS -- no restructuring the HTML. I want the other half of the flexbox to remain centered inside the container.

Essentially, if your screen is 1600px wide, Nick Cage should begin at 0px on the left and stretch to 800px (the center), and then the

.hero-text
should begin at 800px and end at 1400px, as it stays confined to the 1200px width container.

I've commented out a line that I think is key, but I can't get the math right. I just need to offset the image to always be on the left edge of the screen no matter the resolution.



.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/

Answer

No need to use any calculation.

Use relative & absolute positioning to achieve this. See here for additional reading. https://css-tricks.com/absolute-positioning-inside-relative-positioning/

You can position any child element "absolutely" with a relative parent.

In this case, setting the container element to have position: relative; & setting the hero image to have position: absolute; left: 0; Will in fact set place it on the left hand side of the element.

Full 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;
}

Check out this codepen http://codepen.io/anon/pen/NbwVmy to see it working.

Hope this is what you're looking for! ( without messing with the markup of course )

Comments