Why is wp_kses not keeping style attributes as expected?

This is an older question, but here’s the answer for future generations:

WordPress will check the styles against a list of allowed properties and it will still strip the style attribute if none of the styles are safe. The default allow list is:

  • text-align
  • margin
  • color
  • float
  • border
  • background
  • background-color
  • border-bottom
  • border-bottom-color
  • border-bottom-style
  • border-bottom-width
  • border-collapse
  • border-color
  • border-left
  • border-left-color
  • border-left-style
  • border-left-width
  • border-right
  • border-right-color
  • border-right-style
  • border-right-width
  • border-spacing
  • border-style
  • border-top
  • border-top-color
  • border-top-style
  • border-top-width
  • border-width
  • caption-side
  • clear
  • cursor
  • direction
  • font
  • font-family
  • font-size
  • font-style
  • font-variant
  • font-weight
  • height
  • letter-spacing
  • line-height
  • margin-bottom
  • margin-left
  • margin-right
  • margin-top
  • overflow
  • padding
  • padding-bottom
  • padding-left
  • padding-right
  • padding-top
  • text-decoration
  • text-indent
  • vertical-align
  • width

This list is, as with most things in WordPress, filtered! You can add display to it as follows to let your code work as expected:

add_filter( 'safe_style_css', function( $styles ) {
    $styles[] = 'display';
    return $styles;
} );

Leave a Comment