Search code examples
htmlcssribbon

CSS ribbon doesnt scale properly


I have a problem with a responsive CSS ribbon I'm trying to create. I can't get the ribbon to scale down properly for mobile devices. (see screens)

S3 not responsiveFullscreen how it's supposed to look

.ribbon {
  margin: 10px auto;
  padding: 0 10px 0;
  position: relative;
  color: #444;
  background: #fff;
  border: 1px solid #d2d2d2;
  border-radius: 3px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.ribbon h3 {
  display: block;
  height: 30px;
  max-width: 102%;
  line-height: 1.3;
  width: 724px;
  margin: 0;
  padding: 5px 10px;
  position: relative;
  left: -16px;
  top: 8px;
  color: #fff;
  text-shadow: 0 1px 1px #111;
  border-top: 1px solid #922d38;
  border-bottom: 1px solid #922d38;
  background: #922d38;
  background: linear-gradient(top, #383838 0%, #262626 100%);
  border-radius: 2px 2px 0 0;
  box-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
.ribbon h3::before,
.ribbon h3::after {
    content: '';
    display: block;
    width: 0;
    height: 0;
    position: absolute;
    bottom: -11px;
    z-index: -10;
    border: 5px solid;
    border-color: #242424 transparent transparent transparent;    
}
.ribbon h3::before {left: 0;}
.ribbon h3::after {right: 0;}

Does anyone have any suggestions? Link: http://www.welzendesign.com/drielandenpunt/dagje-drielandenpunt/herberg/


Solution

  • The trick here is to extend the <h3> over the edges of the .ribbon by a known amount. You can use position: absolute, and set the left and right properties to a negative value to do that. Then, you can position your pseudo-element triangles to the left and right, too - then, no matter how wide the box is, the ribbon always sticks out the right amount.

    Here's the code (I've simplified to just show the technique - you should be able to add your decorative styles back easily enough). I've used a value of 0.3em for the 'size' of the ribbon overhang, so you can see various combinations of 0.3em and -0.3em - you can scale that up or down to suit.

    .ribbon {
        border: 1px solid #CCC;
        margin: 2em;
        min-height: 20em;
        position: relative;
    }
    
    .ribbon h3 {
        background: red;
        color: #FFF;
        height: 3em;
        left: -0.3em;
        line-height: 3em;
        position: absolute;
        right: -0.3em;
        text-align: center;
        top: 1em;
    }
    
    .ribbon h3::before,
    .ribbon h3::after {
        border-color: transparent;
        border-style: solid;
        bottom: -0.3em;
        content: '';
        display: block;
        height: 0;
        position: absolute;
        width: 0;
    }
    
    .ribbon h3::before {
        border-right-color: black;
        border-width: 0 0.3em 0.3em 0;
        left: 0;
    }
    
    .ribbon h3::after {
        border-top-color: black;
        border-width: 0.3em 0.3em 0 0;
        right: 0;
    }
    

    Here's a demo: https://jsfiddle.net/41unu7ah/