I have this (simplified) situation :
<div class="page-content">
<p>text</p>
<p><img src="" /></p>
<p>text</p>
<!-- ... -->
</div>
And :
.page-content {
padding: 0 20px;
}
.page-content img {
display: block;
margin: 0 auto;
max-width: 100%;
}
This way, I always have a padding inside my .page-content
div (which contains a lot more than what I have copied here). The images cannot take more than the width of the page, minus the padding.
It works great on any screen size.
Example :
However, I want to make the images full-width when on a phone screen (bypassing the parent 20px padding).
i.e. :
I could resolve my problem if the parent (the <p>
) had a negative margin (margin: 0 -20px;
), but the html file is generated by Jekyll from a markdown file, and I can't add classes in it.
I can't find a a way to do this, apart from removing the padding of .page-content
and setting it on each child. Which I would rather not do.
I can't set a fixed width either because I want that to work on every screen size.
Is there a way to select the parent in CSS ? Or another feature I'm unaware of ?
Thanks.
img {
width: calc(100% + 40px);
margin-left: calc(-20px);
margin-right: calc(-20px);
}
I put calc inside the margin-left & right because if the calc function isn't implemented by the browser, it doesn't break design.
You have answered your own question. Remove the padding and set it on the child elements. (or use margin on the child elements as that is what your after really) It is the best solution.
Alternatives: you could use positioning on the image such as position: absolute; this will take it out of the flow of its parent and so ignore the padding, however you would have to know exactly where the image needs to go. Option 1 is much better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With