Search code examples
htmlcsscropborder-radius

Cropping children based on parent's border-radius


In the example snippet below, I try to impose on the last child of the .container element the same border-radius as .container, so that when that last child gets highlighted upon hovering, its background follows the shape of the parent. This seems to work pretty well in this specific case where I've set border-radius in terms of pixels.

.container {
  display: block;
  width: 10em;
  border: 1px solid #999;
  border-radius: 0 0 20px 0;
  box-shadow: 0.1em 0.1em 0.4em black;
}

.entry:hover {
  background-color: #aaa;
}

.entry:last-child {
  border-radius: inherit;
}
<div class="container">
  <div class="entry">
  First
  </div>
  <div class="entry">
  second
  </div>
  <div class="entry">
  third
  </div>
</div>

However, if I use ems, e.g. 2em instead of 20px, things break like this:

enter image description here

I guess this is because the curvature of the parent extends higher than the height of the last child. Indeed if I change 20px to 50px I get this:

enter image description here

Therefore, I think that with 20px I'm just lucky, and that the overall approach of inheriting border-radius in an attempt to have children follow the shape of the parent is wrong. Indeed, in the last example of 50px, the second entry would have to be cropped in away that is simply not obtainable via border-radius.

How can I go about it instead?


Solution

  • Answer:

    Use this css overflow: hidden

    Correct code for OP's question:

    .container {
      display: block;
      width: 10em;
      border: 1px solid #999;
      border-radius: 0 0 2em 0;
      box-shadow: 0.1em 0.1em 0.4em black;
      overflow: hidden;
    }
    
    .entry:hover {
      background-color: #aaa;
    }
    
    .entry:last-child {
      border-radius: inherit;
    }
    <div class="container">
      <div class="entry">
      First
      </div>
      <div class="entry">
      second
      </div>
      <div class="entry">
      third
      </div>
    </div>