0

Here is my situation: I have a wrapper div, a main div inside that and then an <img /> in the main div, whose aspect ratio I have to keep when the window resizes. Width and height of the <img /> are not fixed and may change from one image to another. To keep the aspect ratio of each image preserved, I have used a :after pseudo-element for my wrapper class like this:

wrapper:after{
    padding-top: **%;
    display: block;
    content: '';
}

But since I don't know the width and height of the image, I have to calculate its aspect ratio dynamically using jQuery when the page loads, like this:

$("#ad_image_main").load(function(){
    var h = $(this).height();
    var hh = (h/660)*100;
    /**/
});

#ad_image_main is the id of my <img /> tag

And I have to insert in the /**/ the padding-top value (which is hh) for the wrapper:after-element to get the aspect ratio I want.

How can I do this?

gitcdn
  • 485
  • 3
  • 9
Shanty
  • 3
  • 1
  • 4
  • Any chance of a jsfiddle? – wildandjam Jun 20 '14 at 09:42
  • 1
    You cannot target a pseudo-element with JS/JQ because **it's not in the DOM**. - http://stackoverflow.com/questions/5041494/manipulating-css-pseudo-elements-using-jquery-e-g-before-and-after?rq=1 – Paulie_D Jun 20 '14 at 09:52
  • here it is: http://jsfiddle.net/Vc3G8/ you see there is a `border-bottom` beneath the image, and if i can set the `padding-top` dynamically for `.ad_image:after` i can place this border exactly 10px under the image,with any width and height – Shanty Jun 20 '14 at 09:57

1 Answers1

0

If you search the web, you'll find a couple ways to do this (apply a new class, update the document.stylesheet), but if you just insert a <style> element and write to that, it should do what you want.

Here's a fiddle: http://jsfiddle.net/gGzr9/

And the basic script:

var $style = $('<style>');

$style.appendTo('head');

function updateStyle(px){
    var base = "#wrapper:after{display:block;content:'hello';padding-top:" + px + '%}';
    $style.html(base);
}

// Call updateStyle on resize - no resize, so we'll call it with click
$('button').on('click', function(){
    updateStyle(Math.floor(Math.random() * 100 ));
});
Jack
  • 9,151
  • 2
  • 32
  • 44