Keeping parent div to width and height of wrapping children

前端 未结 3 774
粉色の甜心
粉色の甜心 2021-01-26 02:16

I am building a simple calendar. I am wanting the months to wrap responsively on screen, and the parent container to keep the width and height of its children. For example, if t

3条回答
  •  执念已碎
    2021-01-26 02:38

    So you want the parent to shrink again to fit the width of the children each time a child wraps. I'm afraid there is no pure CSS way to do that.

    Not to change your spec, but I'd suggest keeping the parent at 100% width, and stretching/shrinking the children to fit the parent. I, of course, don't know if that's an option for you, or if the width of the children must be fixed. If it is an option, flexbox or media queries are two good ways to go about it. If it isn't, you'll have to resort to JavaScript.

    Here's an example using media queries and calc():

    .cal {
      box-sizing: border-box;
      position:relative;
      display:inline-block;
      min-width: 100%;
      border:3px solid yellow;
    }
    .month {
      box-sizing: border-box;
      float:left;
      width:calc(100% / 12);
      height:170px;
      border:3px solid red;
    }
    @media (max-width: 900px) { .month { width: calc(100% / 6); } }
    @media (max-width: 600px) { .month { width: calc(100% / 4); } }
    @media (max-width: 400px) { .month { width: calc(100% / 3); } }
    Jan
    Feb
    Mar
    Apr
    May
    Jun
    Jul
    Aug
    Sep
    Oct
    Nov
    Dec

    JSFiddle.

    If you're really wanting the .months to be a fixed width, here's a bit of javaScript that'll do what you want:

    var calcWidth = function() {
        var maxCalWidth = document.body.clientWidth - 9,
            monthWidth = 77,
            monthsPerRow = parseInt(maxCalWidth / monthWidth),
            newWidth = monthsPerRow * monthWidth + 9;
        document.querySelector('.cal').style.width = newWidth + 'px';
    };
    
    calcWidth();
    
    window.onresize = calcWidth;
    

    NOTE that some numbers are hard-coded. You probably don't want to do that, I was just being lazy without jQuery. Here's the JSFiddle for that.

提交回复
热议问题