Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative margin on an image with a 100% width in CSS

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 :

enter image description here

However, I want to make the images full-width when on a phone screen (bypassing the parent 20px padding).

i.e. :

enter image description here

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.

like image 266
Matthieu Oger Avatar asked Oct 02 '13 08:10

Matthieu Oger


2 Answers

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.

like image 197
Tibastral Avatar answered Oct 05 '22 23:10

Tibastral


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.

like image 39
Mike Oram Avatar answered Oct 06 '22 00:10

Mike Oram