Optimizing Jetpack Custom CSS

Jetpack adds a lot of features and performance options to self-hosted WordPress sites, along with it’s own built-in CSS styling. Most of this styling is fairly universal, but some of the top/bottom margins and other elements don’t always blend smoothly with existing site styling. Adding Jetpack-specific styling to an existing stylesheet is fine, but it can be a bit bloated and unneeded if Jetpack isn’t installed on a site. The method below optimizes a custom Jetpack CSS stylesheet to only load if Jetpack is installed and active.

First register and enqueue a CSS file specifically for Jetpack in the theme’s functions.php file using the code below. Note that this conditionally enqueues the CSS file only if Jetpack is active.

<?php
// register optimized styles 
function evo_register_optimized_styles() {
    wp_register_style( 'jetpack-optimized', get_template_directory_uri() . '/assets/css/jetpack.css' );
}
add_action('init', 'evo_register_optimized_styles');
// enqueue optimized styles 
function evo_enqueue_optimized_styles() {
    if ( in_array( 'jetpack/jetpack.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
		wp_enqueue_style( 'jetpack-optimized' );
	}
}
add_action( 'wp_enqueue_scripts', 'evo_enqueue_optimized_styles' );

Then create a jetpack.css file in the directory as registered in the function above. Below is a basic example of some Jetpack-specific custom CSS.

*[class^="wp-block-jetpack-"] {
	margin-top: 2rem !important;
	margin-bottom: 2rem !important;
}
.wp-block-jetpack-slideshow {
	margin-bottom: calc(2rem - 36px) !important;
}
*[class^="wp-block-jetpack-"] *[class^="wp-block-jetpack-"],
*[class^="wp-block-"] *[class^="wp-block-jetpack-"],
.wp-block-jetpack-markdown {
	margin-top: initial !important;
	margin-bottom: initial !important;
}
.wp-block-jetpack-contact-info *[class^="wp-block-jetpack-"] {
	margin-bottom: 0.5rem !important;
}
.sharedaddy {
	padding-top: 0.75rem !important;
}
.jetpack-likes-widget-wrapper iframe {
	margin-top: 0.5rem !important;
}
.sd-title {
	margin-bottom: 0 !important;
}
.sd-content ul li {
	line-height: 0 !important;
	margin-right: 0.25rem !important;
}
.jetpack-comment-likes-widget-wrapper {
	margin-bottom: 0.25rem;
}
.jetpack-comment-likes-widget-wrapper iframe {
	background: #f8f8f8;
	border: 1px solid #cccccc;
	box-shadow: 0 1px 0 rgba(0,0,0,.08);
	border-radius: 3px;
	height: 26px;
	width: 62px;
	margin-top: 3px;
    padding: 1px 0 0 5px;
}
.jetpack-comment-likes-widget-wrapper span.comment-like-feedback {
	display: block;
	font-size: 11px;
}