-1

The content of the post is contained in a div which is centered in the page and thus any images in the post would be constrained to the width of that div. The image below illustrates what I would like to achieve.

A great example of this can be found in the following link but I can't figure out how the JavaScript does it.

https://theintercept.com/drone-papers/manhunting-in-the-hindu-kush/

enter image description here

3 Answers 3

0

I believe you'll want to set the image as a background image on the div (with inline CSS). In your template's PHP you can use the following to get the URL to the full-sized featured image (within the Loop, of course):

$image_url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ) );

Then to assign this image as the background image, you'd do something like:

<div<?php if( $image_url ) { ?> style="background: url(<?php echo $image_url; ?>) no-repeat center center; background-size: cover;"<?php } ?>>
1
  • How does this work in a container like bootstrap? AFAIK the image will be limited to the container.
    – Simon
    Oct 20, 2015 at 8:49
0

If you look at the site and open developer tools, you can see that they're manipulating the margin-left and width css properties for that image via javascript. Probably they're using something like the resize event in jQuery to watch for screen size changes, recalculating the new margin-left and width required and setting them via javascript. The margin-left will vary based on your specific layout, but the screen.width should work no matter what for the width to set for the image.

1
  • Thank you, I had a look with developer tools. But jQuery is not one of my strengths.
    – Simon
    Oct 16, 2015 at 10:04
0

If you are using WordPress I assume you have this class of content: .entry-content and the alignment normally used to display image in full width within content is .alignnone

We can use jquery functions to manipulate the image width including the margin so that the image with alignnone class will be stretched to fit the full width of any browsers. I prefer to do the cache all along with it. Try this:

(function (window, $) {
    'use strict';

    // Cache element
    var document = window.document;

    var dis = function () {
        var cache = {};

        function init() {

            cacheElements();

            bindEvents();
        }

        function cacheElements() {
            cache.$window       = $(window);
            cache.$document     = $(document);

            // Test for iPod and Safari
            cache.isiPod        = isiPod();
            cache.isSafari      = isSafari();
            cache.$body         = $('body');
            cache.$isHomepage   = cache.$body.hasClass('home');
            cache.$isSingle     = cache.$body.hasClass('single');
            cache.$entryContent = cache.$body.find('.entry-content'); // class for default WordPress' post
            cache.$fullImages   = cache.$entryContent.find('.alignnone'); // class for image with none alignment. Images with this alignment will be the target of full width images displayed within content
            cache.$windowWidth  = cache.$window.width();

            cache.$others       = [];
            cache.$page         = 1;

            cache.windowHeight  = (true === cache.isiPod && true === cache.isSafari) ? window.screen.availHeight : cache.$window.height();
        }

        /**
         * Setup event binding.
         *
         */
        function bindEvents() {
            // Enable the mobile menu
            cache.$document.on('ready', function() {
                setupRetinaCookie();
                setupFullWidthImages();
            });

            cache.$window.on('resize', function() {
                setupFullWidthImages();
            });

            var lazyResize = debounce(resetHeights, 200, false);
            cache.$window.resize(lazyResize);

        }

        function setupFullWidthImages() {
            cache.$fullImages.each(function(){
                var _this = $(this);

                if( _this.hasClass('wp-caption') ) {
                    _this.css( { 'margin-left': ( ( cache.$entryContent.width() / 2 ) - ( cache.$window.width() / 2 ) ), 'max-width': 'none' });
                    _this.add(_this.find('img')).css( 'width', cache.$window.width());
                }else{
                    _this.css( { 'margin-left': ( ( cache.$entryContent.width() / 2 ) - ( cache.$window.width() / 2 ) ), 'max-width': 'none', 'width': cache.$window.width() });
                }
            });
        }

        /**
         * Set 'retina' cookie if on a retina device.
         *
         */
        function setupRetinaCookie() {
            if( document.cookie.indexOf('retina') === -1 && 'devicePixelRatio' in window && window.devicePixelRatio === 2 ){
                document.cookie = 'retina=' + window.devicePixelRatio + ';';
            }
        }

        /**
         * Check if device is an iPhone or iPod
         *
         */
        function isiPod() {
            return (/(iPhone|iPod)/g).test(navigator.userAgent);
        }

        /**
         * Let's check if browser is Safari
         *
         */
        function isSafari() {
            return (-1 !== navigator.userAgent.indexOf('Safari') && -1 === navigator.userAgent.indexOf('Chrome'));
        }

        /**
         * Calculate and set the new height of an element
         *
         */
        function setDivHeight(element, others) {
            // iOS devices return an incorrect value with height() so availHeight is used instead.
            var windowHeight = (true === cache.isiPod && true === cache.isSafari) ? window.screen.availHeight : cache.$window.height();
            var offsetHeight = 0;

            // Add up the heights of other elements
            for (var i = 0; i < others.length; i++) {
                offsetHeight += $(others[i]).outerHeight();
            }

            var newHeight = windowHeight - offsetHeight - parseInt( $('html').css('margin-top') );
            // Only set the height if the new height is greater than the original
            if (newHeight > 0) {
                $(element).outerHeight(newHeight);
            }
        }

        /**
         *
         * Based on Underscore.js.
         *
         * @link    http://underscorejs.org/#debounce
         *
         */
        function debounce (func, wait, immediate) {
            var timeout, args, context, timestamp, result;
            return function() {
                context = this;
                args = arguments;
                timestamp = new Date();
                var later = function() {
                    var last = (new Date()) - timestamp;
                    if (last < wait) {
                        timeout = setTimeout(later, wait - last);
                    } else {
                        timeout = null;
                        if (!immediate) {
                            result = func.apply(context, args);
                        }
                    }
                };
                var callNow = immediate && !timeout;
                if (!timeout) {
                    timeout = setTimeout(later, wait);
                }
                if (callNow) {
                    result = func.apply(context, args);
                }
                return result;
            };
        }

        // Initiate the actions.
        init();
    };

    // Instantiate the "class".
    window.dis = new dis();
})(window, jQuery);

That should do the job. Using those functions, every image with align none alignment will be stretched into full width to fit the browser.

If others have any simple recommendations please add in here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.