Site logo

Archived topic

suggested generate_padding_css() improvement

1 reply · Started by Simon on January 3, 2018

Viewing posts 1–2 of 2

Hi Tom,

I have a suggested function improvement for you:
generate_padding_css() in theme-functions.php only shorthands the css values if they are all the same.
This version will handle all the valid shorthands, and produce the smallest possible css size.
Note: a css value of '0' doesn't need a unit suffix, and the 'left' variable has a space added to the end so the final trim() can remove it, and the space after the '0's makes the empty() function behave.

function generate_padding_css( $top, $right, $bottom, $left ) {
  $padding_top    = ( absint( $top    ) > 0 ) ? absint( $top    ) . 'px ' : '0 ';
  $padding_right  = ( absint( $right  ) > 0 ) ? absint( $right  ) . 'px ' : '0 ';
  $padding_bottom = ( absint( $bottom ) > 0 ) ? absint( $bottom ) . 'px ' : '0 ';
  $padding_left   = ( absint( $left   ) > 0 ) ? absint( $left   ) . 'px ' : '0 ';
  // shorthand the values
  if ( absint( $padding_right ) === absint( $padding_left ) ) {
    $padding_left = '';       // L == R, only need 3 values
  }
  if ( empty( $padding_left ) && ( absint( $padding_top ) === absint( $padding_bottom ) ) ) {
    $padding_bottom = '';     // L == R  &&  T == B,  only need 2 values
  }
  if ( empty( $padding_bottom ) && ( absint( $padding_top ) === absint( $padding_right ) ) ) {
    $padding_right = '';      // L == R == T == B, only need 1 value
  }
  return trim( $padding_top . $padding_right . $padding_bottom . $padding_left ); // trim final trailing space;
}

Simon

This archived topic is closed to new replies.