-1

I am (was) looking for a way that my images would be full width despite the body padding. And, I wanted my images to also not be too tall.

Making matters more difficult, (a) all of the images live inside of <p> tags and I can't (easily) assign classes, etc to them. That is because the pages are generated from a Markdown conversion and I wanted to avoid having to apply a ton of regex (though I was willing to if need be).

The requirements were basically that the text be padded inside the body (but not via a p margin so I didn't have to deal with non-paragraph elements). And, I wanted it such that the maximum height was some percentage of the current width. Finally, in addition to trying to avoid touching the HTML, I also didn't want to add any js if I could help it.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Justin Winokur
  • 91
  • 1
  • 1
  • 7
  • 2
    It's perfectly fine to post self-answers, so thanks for this already. However, your question should still be answerable by anyone, so write it as if you really do need someone else than yourself to answer it (full details, maybe a [MCVE] etc.) and moreover, no need for the header stating you already solved it, nor to all the past tense. – Kaiido Oct 06 '19 at 06:17

1 Answers1

1

The following is my solution. It still needs some tinkering since you can become height-constrained before width-constrained with square images but if nothing else it is a start. Again, this may be super obvious to those more experienced.

Define the folliwng

  • $pad to be the padding of the body (2em)
  • $body_width to be the width of the body element (900px
  • $mh is the fraction to set the max height. Again, this is personal preference for the type of images you care about. I'll do 0.9 in this example.
body {
  margin: 1em auto auto;
  max-width: 900px; /* $body_width */
  padding: 0.1em 2em 2em; /* $pad $pad */
}

video,img{
    border: 0;
    max-width: calc(100% + 4em); /* + 2*$pad */
    max-height: 810px; /* $mh * $body_width 
    display: block;

    /* From [1] */
    position: relative;
    left: 50%;
    transform: translateX(-50%);
    display: block;
}

[reference 1]

But I also wanted to handle tall screens with width less than max (i.e. mobile).

@media only screen and (max-width : 900px) { /* $mh*$body_width */
   img,video {
        max-height: 100vw;
    }
}

It works by first making the image max width go beyond the padding and then using transform to center it.

I hope this helps someone in the future. It could have saved me a day!

Justin Winokur
  • 91
  • 1
  • 1
  • 7
  • `* {border: 0; margin: 0; padding: 0;}` and don't forget `object-fit`: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit. Go through the lists of CSS properties, selectors, etc and other languages that you work with. Be aware of the tools available for you to use. Good luck. – John Oct 06 '19 at 06:22