简体   繁体   中英

Using javascript to add inline css style with height dynamically calculated from container width

Our WordPress theme uses the main image of the post as a background image on the blog page. To make this work the developers set a fixed height like so:

.hentry .entry-thumbnail-wrap {
    background-size: cover;
    background-position: center;
    height: 336px;
}

On mobile devices the image is cropped, since the height is fixed. As a quick and dirty workaround I set some CSS media queries, but I would prefer a better solution.

I tried javascript and while I can easily get the width of the container, the script won't add the inline style.

To get the width of the container I use:

var box = document.getElementsByClassName("entry-thumbnail-wrap")[0];

This fetches the actual width of the first DIV with the class "entry-thumbnail-wrap"

Now, I can calculate the height:

var height = box.offsetWidth / 2.5 + "px";

I can check the result, and it shows the correct value:

window.alert(height);

Now, I would like to add this to the already existing inline style:

box.style.cssText += height + ';';

That does not work. For test purposes, I tried a simple rule like so:

box.style.cssText += 'color:red;';

That does not work either. Nothing is added to the inline style. What am I missing?

Why not try to enforce and aspect ratio with a pseudo element (in this case a :before ). As long as no other content is inside your .entry-thumbnail-wrap - because the pseudo element will fill the aspect ratio you want and push everything else out of the way.

 .entry-thumbnail-wrap { background-size: cover; background-position: center; height: auto; }.entry-thumbnail-wrap:before { content: ''; width: 100%; /* This will give it an aspect ratio of 2/1 */ padding-bottom: 50%; display: block; }
 <div class="entry-thumbnail-wrap" style="background-image: url(http://placehold.it/300x300)"></div>

This makes it a fixed aspect ratio at any size. You could potentially limit it with a max-height or something on your .entry-thumbnail-wrap class.

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