我正在创建一个使用百分比来调整元素大小的响应式网格系统系统。我尝试用浮点数、内联块和表格来构建它。我确定我想坚持使用 inline-block,因为它允许我将项目垂直和水平居中。我在不使用边距的情况下构建了我的设计。我正在使用边框模型,因此填充和边框不会折叠行。
但是,我想升级我的网格系统以允许您在不破坏行的情况下设置边距。基本上是一个 jquery 自定义构建的“box-sizing: margin-box;”。
我希望我可以使用 jquery 从容器的百分比宽度中减去边距的百分比宽度。然而,这本身并不能很好地工作,因为 inline-block 增加了额外的空白。因此,除了我目前的计划之外,我还使用 jquery 从 margin-right 中减去额外的空白。我真的让它工作了!它做我想做的事,但我面临一个小问题。
计算不够精确,行最终会出现彼此不同的几个像素。这意味着我在每一行的末尾都没有得到直线。整个行的长度不同。如何使计算足够精确以准确排列?
这是代码:
     boxsizing = function(container){
     jQuery(container).each(function() {
      var el = jQuery(this);
      el.css('width', '');
      el.css('margin-right', '');
      var parentWidth = el.parent().width();
      var childWidth = el.outerWidth(false);
      //finds ratio of child container to parent container
      var childDecimal = (childWidth / parentWidth);
      //converts child container to a decimal
      childDecimal = Math.round(childDecimal*10000);
      //gets font size
      var fontSize = el.css('font-size');
      //removes px from the end
      var fontSize = fontSize.slice (0, -2);
      //calculates white space on the right of each div
      var whiteSpace = 0.29*fontSize;
      var fontDecimal = whiteSpace / parentWidth;
      //converts white space to a decimal
      fontDecimal = Math.round(fontDecimal*10000)
      //subtracts extra white space from margin-right
      var newMarginRight = el.css('margin-right');
      var newMarginRight = newMarginRight.slice (0, -2);
          newMarginRight = Math.round(newMarginRight);
          newMarginRight = newMarginRight - whiteSpace;
          newMarginRight = newMarginRight / parentWidth;
          newMarginRight = Math.round(newMarginRight*10000);
          newMarginRight = newMarginRight/100;
      //finds margin to parent ratio
      var marginDecimal = (el.outerWidth(true) - childWidth)/parentWidth;
      //converts margin to decimal form
      marginDecimal = Math.round(marginDecimal*10000);
      //take previous width and subtract margin from it
      var newWidth = (childDecimal - marginDecimal)/100;
      //set the element's width to the new calcualted with and set margin right to the updated value
      el.css('width', newWidth + "%");
      el.css('margin-right', newMarginRight + "%");
     });
    }
    jQuery(window).load(function() {
        boxsizing('.margins');
    });