user12828557
user12828557

Reputation:

How do I make a div height or position adapt to its content's relative position

so I've tried to find an answer to this question and I can't. Maybe I'm just not wording it properly.

So here's my situation. I have a website that is made responsively using rows and columns.

In one of my columns, I want the image it contains to be offset just a little as to overlap on the column above it.

Here's what it looks like (note that red borders have been added to every columns to make it more obvious):

enter image description here

So my issue is this. Whenever I use {position: relative; top: -20%;}, it creates an empty space below the image that I just can't figure out how to remove (highlighted in blue).

The code has many different CSS files so I'll have to just link the HTML portion and a summary of the CSS to avoid needlessly making this complicated.

.resize {
  height: 80%;
}

#is1-img-1 {
  height: auto;
  max-width: 100%;
  position: relative;
  top: -20%;
}
<section id="index-section-1" class="large-padding">
  <!-- Left: image, Right: text -->
  <div class="row">
    <!-- Row 1/2 -->
    <div class="col-s-12 col-l-6 resize">
      <!-- Row content: image -->
      <img id="is1-img-1">
    </div>
    <div class="col-s-12 col-l-6">
      <!-- Row content: text -->
      <img class="line">
      <!-- For line svg - separator -->
      <h2>Enjoyable place for all the family</h2>
      <p>Our relaxed surroundings make dining with us a great experience for everyone. We can even arrange a tour of the farm before your meal.</p>
    </div>
  </div>
  <div class="row flip-on-mobile">
    <!-- Row 1/2 -->
    <div class="col-s-12 col-l-6">
      <!-- Row content: text -->
      <img class="line">
      <!-- For line svg - separator -->
      <h2>The most locally sourced food</h2>
      <p>All our ingredients come directly from our farm or local fishery. So you can be sure that you’re eating the freshest, most sustainable food.</p>
    </div>
    <div class="col-s-12 col-l-6">
      <!-- Row content: image -->
      <img id="is1-img-2">
    </div>
  </div>
</section>

I assumed, if I move the div's content 20% away, then making the div itself 80% of the height should work, but when I do that, it completely overwrites the {position: relative; top: -20%}. It just puts the image inside the div again.

Upvotes: 0

Views: 163

Answers (1)

arieljuod
arieljuod

Reputation: 15838

Adding an answer for completeness.

A solution to the problem can be to use a negative margin of 20%:

{
  margin-top: -20%;
}

Regarding the original CSS: it generates that extra white space at the bottom of the image because of how position: relative works. The element still uses the original space to affect the layout, when moving it using the top/left/right/bottom values it will only move the visual but it WILL NOT change the calculated layout.

Upvotes: 1

Related Questions