MrCarrot
MrCarrot

Reputation: 2768

Stretch left side of image outside container to edge of the page

Normally I'm quite good at CSS but I cannot figure out how to do this particular layout.

I have a container with a maximum width of 1,400 pixels. The left and right margin are set to auto so when the viewport is above 1,400 pixels the container is centralised.

I then have an image outside the container with a div next to it, the image occupying 40% of the viewport, the div taking up the remaining 60% of the viewport.

What I want, is a div inside the 60% portion, that doesn't go any wider than the right-hand edge of the 1,400 pixel container above.

A diagram might make things clearer:

enter image description here

My CSS so far:

div.container {
  max-width: 1400px;
  margin: 0 auto;
}

img {
  display: inline-block;
  width: 40%;
}

div.right {
  display: inline-block;
  width: 60%;
}

div.inner {
  ???
}

For div.inner I've tried variations of percentages and calc but to no avail. For clarification, everything on the layout is fine apart from the pink box which I cannot get to line up with the right-hand edge of the red box.

Upvotes: 2

Views: 2497

Answers (1)

Temani Afif
Temani Afif

Reputation: 273032

Since the red div has a max-width of 1400px then the space left will be 100vw-1400px so the space on one side will be the half. You can simply make the padding-right of the green box to be (100vw - 1400px)/2 which is also 50vw - 700px.

Here is an example where I consider 600px instead of 1400px:

* {
  box-sizing:border-box;
}
body {
  margin:0;
}

div.container {
  max-width: 600px;
  margin: 0 auto;
  background:red;
  height:50px;
}

img {
  display: inline-block;
  width: 40%;
  height:50px;
  background:yellow;
}

div.right {
  display: inline-block;
  width: 60%;
  padding-right:calc(50vw - 300px);
  background:green;
}

div.inner {
  background:blue;
  height:50px;
}
<div class="container">
</div>
<img src="" ><div class="right">
<div class="inner">
</div>

</div>

You can also use it as margin-right of the inner div:

* {
  box-sizing:border-box;
}
body {
  margin:0;
}

div.container {
  max-width: 600px;
  margin: 0 auto;
  background:red;
  height:50px;
}

img {
  display: inline-block;
  width: 40%;
  height:50px;
  background:yellow;
}

div.right {
  display: inline-block;
  width: 60%;
  background:green;
}

div.inner {
  background:blue;
  height:50px;
  margin-right:calc(50vw - 300px);
}
<div class="container">
</div>
<img src="" ><div class="right">
<div class="inner">
</div>

</div>

Upvotes: 6

Related Questions