htmlcssflexboxcss-gradients

CSS- Style "handles" above div without css absolute


I styled a "Calendar" div with "handles" above.

calendat with handles

This is created with setting 2 div 3*3 px with black background and placing them in absolute positions exactly above the top of calendar div inside a parent div which is position relative.

This calendar is located in absolute location above an image.

This works, but it feels very "hard coded" because every change in the calendar div will break the display because the "handles' would sill in the same place, while the calendar top border can move.

How can I get the same "handles" style on a top of calendar div itself so changes on the calendar CSS height won't effect the "handles"?


Solution

  • You can use a psuedo-element like so - see working example below.

    The .cal::before element is a 3px tall box (height) with 3px black borders on the left and right.

    It is absolute positioned off the parent calendar element by -6px on the Y axis (top) so it goes past the calendar's top border, and 3px left and right of the calendar bounds.

    .cal {
      border: 3px solid #000;
      display: inline-block;
      font-family: sans-serif;
      position: relative;
      text-align: center;
    }
    
    .cal span {
      /* day */
      display: block;
      font-size: 10px;
      padding: 3px 10px;
    }
    
    .cal b {
      /* date number */
      display: block;
      border-top: 3px solid #000;
      padding: 5px;
    }
    
    .cal::before {
      /* handles */
      content: '';
      position: absolute;
      height: 3px;
      top: -6px;
      border-left: 3px solid #000;
      border-right: 3px solid #000;
      left: 3px;
      right: 3px;
    }
    <div class="cal">
      <span>SUN</span>
      <b>3</b>
    </div>
    
    <br><br>
    
    <div class="cal">
      <span>TALLER</span>
      <b>3</b>
      <b>4</b>
      <b>5</b>
    </div>