简体   繁体   中英

Adjust image size to suit baseline grid in CSS

I'm working on a website with a set baseline of 14px which then extrapolates out to various sizes (double, triple, etc.). This has been great while I was only focused on getting the text correct and fixing the issues that inevitably happen with trying to get this right.

Now I am at an awkward point though as I try to automatically format images to fit the layout correctly. The images will be in the HTML and I won't have control over their physical dimensions. What is the best way to ensure these images follow my baseline grid?

For example, if I have an image that is 400px tall, I need to ensure that it is displayed at 392px which would be 28x the baseline (and therefore match with the text). This needs to work no matter the size of the image, always preferring the rounded down fraction (ie, 400px is 28.57... so should come to 14x28). Width should then follow suit.

I'm happy to use JS to do this, I am guessing it won't be something I can achieve purely in CSS because of the dynamic image size. Any help greatly appreciated!

For anyone trying to achieve something similar to this, a friend helped me out and we came up with a solution that will resize respecting the image proportions based on your baseline as below.

$( document ).ready(function() {
    $('img').each(function() {
        var b = 14,
            h = $(this).height(),
            x = Math.floor(h/b)*b;
        $(this).css('height',x);
    });
});

Change the b variable to match your baseline and now all images will be resized to suit regardless of how tall they are. The only issue is if you need 100% width then you need to look at a masking DIV but I didn't need that for this particular project. Very useful though for those pedantic about their baselines like me!

Following @teknetia's idea. You could ignore the height of the image and instead dynamically change the margin so it pushes the next bit of content down to the next baseline.

$('img').each(function() {
    var b = 24,
        h = $(this).height(),
        x = (b*Math.ceil(h/b))-h;
        console.log(x);
    $(this).css('margin-bottom',x);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM