Search code examples
htmlcssposition

Move element to right margin without removing from HTML flow with CSS


I have a column of fixed width centered on the page. Since the viewport varies, the margin is unknown. I would like to move it to the left edge of the screen without removing it from the HTML flow.

<main class="centered" style="width:750px;margin-left:auto;margin-right:auto">
...
  <figure class="imagefullwidth" style="width:100vw">
    <img src="image.jpg">
  </figure>
...
</main>

That should look something like:

       _______main_______
      |                 |
      |                 |
 _____|______figure_____|_____     
|                             |
|                             |     
|                             |     
|_____________________________|     
      |                 |
      |                 |
      |                 |
      |_________________|

Of course, I tried position: absolute; left: 0 on <figure> but that took it out of the HTML flow. I tried position: absolute; on the image and though I can create a larger image than its container, left:0 only puts the image at the left edge of the <main> (plus that allowed <figure> to collapse to height 0 and I don't know the height of the image to give it a height).

Negative margins don't help because I don't know the width of the margin at any particular viewport width. float: left doesn't work because it floats within its container.

I can't modify the HTML because it comes from a CMS. But there are lots of wrappers and stuff I can style.

Can you think of a way to do this with pure CSS, without JS?

Attempting to make the image larger than its container - left:0 can't break out of main container


Solution

  • Based on the html and visual example provided the below css seems to accomplish what you're after. JSFiddle example

    .centered {
      background-color: gray;
      width: 100% !important;
      max-width: 750px;
    }
    
    .imagefullwidth {
      width: initial !important;
    }
    
    .imagefullwidth img {
      position: relative;
      left: 50%;
      transform: translateX(-50%);
      width: 100vw;
      height: auto !important;
    }