With some providers (Youtube from what I could find) we have aspect ratio problems when we render them using the OembedFormatter.

The problem I discovered is primarily with Youtube: the resource returned from Youtube does not contain the requested width/height but the default size (or simply A size) of the video. This is fine if the formatter is configured to use a width and height that corresponds to the aspect ratio of that particular video. But that won't ever happen. When we configure the formatter to a specific max width but a height of 0, there is at least some expectation that the rendered iframe maintains the aspect ratio. At the moment, since the formatter is configured to a *max* width and no *max* height the iframe gets that that width attribute and the default height that comes from the resource. So the result is that the iframe size doesn't match the size of the video. A solution for this is to calculate the aspect ratio of the video using the values in the resource and recalculate the height attributed based on that in case the max height is configured as 0.

Discussing with @phenaproxima we might make a checkbox (default unchecked) for this in order to prevent BC.

Other providers, like Vimeo, may not have this issue. So in these cases this should not apply. But youtube is pretty important.

Issue fork drupal-3060968

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

Upchuk created an issue. See original summary.

upchuk’s picture

StatusFileSize
new5.27 KB
upchuk’s picture

Title: Responsive oEmbed videos that maintain aspect ratio » Some oEmbed videos do not maintain aspect ratio
Issue summary: View changes
Issue tags: -DevDaysTransylvania +@DevDaysTransylvania
StatusFileSize
new8.35 KB
new7.36 KB

OK, updated the patch to clean up the tests + make the aspect ratio maintenance a formatter option to ensure full BC just in case.

Also updated the issue title and description to split out the responsive part of the container iframe that went into #3061134: oEmbed videos are not fully responsive.

phenaproxima’s picture

I think, overall, I like this idea and think it would be useful. If we can do it in a backwards-compatible way, then this will improve the experience of adding and using remote videos -- it will bring them closer to the "it just works" holy grail.

Also...you wrote tests. Thank you!!! :) Will do a more detailed review when I have a little more bandwidth.

phenaproxima’s picture

Issue tags: -@DevDaysTransylvania +DevDaysCluj
phenaproxima’s picture

Category: Bug report » Feature request

Also, re-categorizing as a feature request, since this technically is not a bug.

rosinegrean’s picture

Issue tags: -DevDaysCluj +DevDaysTransylvania
yogeshmpawar’s picture

Assigned: upchuk » yogeshmpawar
yogeshmpawar’s picture

Assigned: yogeshmpawar » Unassigned
StatusFileSize
new8.35 KB
new1.32 KB

Resolved some coding standard issues & added an interdiff as well.

phenaproxima’s picture

Issue tags: +oembed

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

mrpauldriver’s picture

Other providers, like Vimeo, may not have this issue. So in these cases this should not apply. But youtube is pretty important.

Confirm that Vimeo has similar problems.

mrpauldriver’s picture

StatusFileSize
new167.92 KB
new494.73 KB
new295.01 KB

Tested against 8.8.0-beta1 on simplytest.me

Vimeo
When maximum width value is empty and maintain aspect ratio checkbox is enabled.
oembed iframe does not display the video, but instead shows the test site in an iframe. Screenshot 1

When maximum width value is provided (of 1024px) and maintain aspect ratio checkbox is enabled.
Video scales to fill its container, but white space is seen above and below the video when the viewport is scaled down. Screenshot 2

YouTube
When maximum width value is empty and maintain aspect ratio checkbox is enabled.
As with vimeo the iframe does not display the video and again shows the test site in an iframe. Same as Screenshot 1

When maximum width value is provided (of 1024px) and maintain aspect ratio checkbox is enabled.
Video scales to fill its container, but letterbox effect is seen with black space above and below the video when scaled down. Screenshot 3

Patch does not apply to 8.9.x on simplytest.me

mrpauldriver’s picture

Not sure how long this simplytest.me link will stay live, but I remember hearing that they were extending the 24 hour thing

https://stm5dd3b08bb00d5-uhwftnqckcswi0euo3vliwyv3e9pzcxb.tugboat.qa/node/1

U: admin
P: admin

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

jdhaire’s picture

New to this space, but we have this issue. Can anyone point me in the direction of a solution? Thanks in advance!

phenaproxima’s picture

Category: Feature request » Bug report
Issue tags: +Media Initiative, +Triaged Media Initiative issue

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

karlshea’s picture

How are people handling this in the real world? I'm trying to move some sites off of Video Embed Field, and since this has been an issue in Drupal core for like two years now it's obvious there's some way around it otherwise it would have gotten fixed already.

heddn’s picture

Issue summary: View changes
Status: Needs review » Needs work
StatusFileSize
new18.8 KB
new5.78 KB
+++ b/core/modules/media/src/Plugin/Field/FieldFormatter/OEmbedFormatter.php
@@ -194,6 +195,17 @@ public function viewElements(FieldItemListInterface $items, $langcode) {
+          $max_height = number_format(round($max_width / $ratio));

+++ b/core/modules/media/tests/src/FunctionalJavascript/MediaSourceOEmbedVideoTest.php
@@ -43,6 +43,85 @@ protected function initConfig(ContainerInterface $container) {
+    $height = number_format(round(800 / $ratio));

This adds a comma in large numbers (1,024) , why are we using number_format? round seems like it would be enough.

The settingsSummary also is off.
Here we set the aspect ratio, after setting a hight of 1100 (which gets hidden):

But then the summary still says max dimensions since Maximum height was left in the form before selecting the checkbox toggle for aspect ratio:

heddn’s picture

Status: Needs work » Needs review
StatusFileSize
new4.42 KB
new9.37 KB

This seems to resolve all the feedback from #20 and #13. I don't have the whitespace/blackspace above/below the video in my site.

heddn’s picture

StatusFileSize
new9.55 KB

Fixed patch. Interdiff was fine.

Status: Needs review » Needs work

The last submitted patch, 22: 3060968-22.patch, failed testing. View results

heddn’s picture

Issue tags: +Novice

Seems like a novice to fix the failing test. Tagging

anmolgoyal74’s picture

Status: Needs work » Needs review
StatusFileSize
new9.47 KB
new1.27 KB
mrpauldriver’s picture

I am testing the latest patches against Drupal 9.1 and 9.2 but do not see any improvement when compared with my observations made in #13.

I'm slightly reluctant to formally mark as Needs work when I am up against core maintainers/contributors, but I feel like saying this needs work :)

mrpauldriver’s picture

By using the css below in my theme, I am able to resolve all the problems. Could something like this be included in the core media module?

The padding-top value is variable, but pretty sure that 16:9 would cover the majority of remote video sources.

.field--name-field-media-oembed-video {
  position: relative;
  overflow: hidden;
  width: 100%;
  padding-top: 56.25%; /* 16:9 Aspect Ratio (divide 9 by 16 = 0.5625) */
}

/* Then style the iframe to fit in the container div with full height and width */
.media-oembed-content {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
}

Source. https://www.w3schools.com/howto/howto_css_responsive_iframes.asp

playful’s picture

#27 worked perfectly for me without applying any patch.

extect’s picture

@MrPaulDriver: Thank you!! #27 works perfectly!

jonesui’s picture

#27 is also working for me without patching.

kleiton_rodrigues’s picture

StatusFileSize
new223.81 KB

@MrPaulDriver: Tks #27 works good!

ranjith_kumar_k_u’s picture

StatusFileSize
new181.74 KB
new328.76 KB

#27 works fine.

Before using css
before

After using css
after

kreatil’s picture

#27 solved it in my use case. Sometimes it's the simple solutions! Thanks!

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

delmarr’s picture

StatusFileSize
new149.31 KB

#27 works well when using a media field, however when embedding a remote video in the wysiwyg, the editor window will still display a small thumbnail and which won't reflect the published page that displays the full width video.

I suspect a developer may need to update the CSS provided by ckeditor /core/modules/ckeditor/css/ckeditor-iframe.css and — depending on your setup — possibly update a twig template to provide the field name i.e., .field--name-field-media-oembed-video

wrd’s picture

I first tried the patch in #25, and got what seems like a peculiar result. The max width on the field formatter was set to 1180px (because on a page with a full-width layout, that is indeed the widest possible element on this site). I then placed a video in a layout with a 2/3-1/3 column layout, in the 2/3 column, with a width of 780px. What I wound up with was a video with a height of 664px, rather than the expected 439px. It appears that the height was based on the max width rather than the actual width.

I then tried the styling solution in #27, and it works very nicely, although I expect we'll need to adjust it should we need to use any videos that aren't 16x9.

yazzbe’s picture

#27 worked for me :)

camhoward’s picture

Many thanks to MrPaulDriver for the CSS in #27 which is a huge help!

A quick note that the first class name in his example:
.field--name-field-media-oembed-video
may not be the same in all themes.

In my themes, I found either one of the following classes works when adding a video to the body field via the Media Library:

.field-media--field-media-oembed-video
or
.field-name-field-media-oembed-video

The second class name in his example:
.media-oembed-content
seems to be more consistent across themes.

Hope this helps!

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

gonssal’s picture

CSS in #27 works fine unless you set a caption to the video. For some reason core's stable theme sets display: table to the .caption class, which was a pretty bad decision honestly.

So if you want the code in #27 to work with captions, you have to add:
.caption { display: block; }

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

chris matthews’s picture

In #4 Adam (phenaproxima) said,

I think, overall, I like this idea and think it would be useful. If we can do it in a backwards-compatible way, then this will improve the experience of adding and using remote videos -- it will bring them closer to the "it just works" holy grail.

Question is, what is the proper path for this feature request as far as potentially getting it committed to core?

(1) continuing to work on the initially proposed solution in the latest patch
or
(2) implementing a new solution using the custom CSS outlined in #27, #38 and #40 ?

stevenx’s picture

#27 works good for me for instagram, twitter, youtube, tiktok, giphy, facebook all embeded with https://www.drupal.org/project/oembed_providers module

phenaproxima’s picture

Status: Needs review » Needs work

OK, so that's a large number of people reporting that #27 is a good fix for this problem. I have no objections to adding that CSS to the core media module. Would someone be willing to create a patch or merge request for it (against Drupal 9.5.x)?

chris matthews’s picture

Please note the comment in #35

#27 works well when using a media field, however when embedding a remote video in the wysiwyg, the editor window will still display a small thumbnail and which won't reflect the published page that displays the full width video.

I suspect a developer may need to update the CSS provided by ckeditor /core/modules/ckeditor/css/ckeditor-iframe.css and — depending on your setup — possibly update a twig template to provide the field name i.e., .field--name-field-media-oembed-video

phenaproxima’s picture

Issue tags: +Needs title update, +Needs issue summary update, +Needs follow-up

In that case, let's still proceed with a patch and rescope this issue to deal only with media fields. We can file a follow-up to deal with this in CKEditor.

camhoward’s picture

When a patch is created using the code in #27, is there a way to account for theme differences as described in #38 and #40? Or does that become too complex?

phenaproxima’s picture

Probably could use advice from @lauriii or another front-end expert, but my guess is that we'd want to add the CSS to the Media module, then override that if and as needed in core themes.

luke.leber’s picture

Given this feature relies on resource metadata, should we postpone on https://www.drupal.org/project/drupal/issues/2983456 to prevent stale aspect ratios from becoming a problem?

We already have a ton of communication issues with our social media teams regarding making changes on the YT side that our content management team aren't aware of.

cgmonroe’s picture

Patching core is a no-go for me. Also, I needed to deal with multiple aspect ratios. I found the following solution:

Created a module with its own OEmbedFormatter field plugin based on the core version with the patch from #25, with different plugin id and settings file.

I added code to this to include an aspect-x-x (e.g. aspect-16-9) class to the iframe, e.g.:

        // calculate the aspect ratio if:
        // - the formatter is configured to do so (and no max height)
        // - the resource width is not the same as the max width that was
        // requested.
        if ($this->getSetting('maintain_aspect_ratio') && !$max_height && $resource->getWidth() !== $max_width) {
          $ratio = $resource->getWidth() / $resource->getHeight();
          $max_height = round($max_width / $ratio);
          if ($ratio > 1.7) {
            $aspect = 'aspect-ratio-16-9';
          }
          elseif ($ratio > 1.55) {
            $aspect = 'aspect-ratio-8x5';
          }
          elseif ($ratio > 1.4) {
            $aspect = 'aspect-ratio-3-2';
          } elseif ($ratio > 1.2) {
            $aspect = 'aspect-ratio-4-3';
          }
          else {
            $aspect = 'aspect-ration-1-1';
          }
        }

Plus some code to add this class to the element.

        $classs = ['media-oembed-content'];
        if ($aspect) {
          $classs[] = $aspect;
        }

        // Render videos and rich content in an iframe for security reasons.
        // @see: https://oembed.com/#section3
        $element[$delta] = [
          '#type' => 'html_tag',
          '#tag' => 'iframe',
          '#attributes' => [
            'src' => $url->toString(),
            'frameborder' => 0,
            'scrolling' => FALSE,
            'allowtransparency' => TRUE,
            'width' => $max_width ?: $resource->getWidth(),
            'height' => $max_height ?: $resource->getHeight(),
            'class' => $classs,
          ],

Created a field--media--field-media-oembed-video.html.twig template based on the default field.html.twig template that adds the aspect class from the iframe element to the parent div, e.g.:

  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
    label_display == 'inline' ? 'clearfix',
    element.0['#attributes'].class.1
  ]

Then added CSS for these classes based on: https://www.w3schools.com/howto/howto_css_responsive_iframes.asp

.field--name-field-media-oembed-video {
  position: relative;
  overflow: hidden;
  width: 100%;
}
.media-oembed-content {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
}
.field--name-field-media-oembed-video.aspect-ratio-16-9 {
  padding-top: 56.25%;
}
.field--name-field-media-oembed-video.aspect-ratio-4-3 {
  padding-top: 75%;
}
.field--name-field-media-oembed-video.aspect-ratio-3-2 {
  padding-top: 66.66%;
}
.field--name-field-media-oembed-video.aspect-ratio-8-5 {
  padding-top: 62.5%;
}
.field--name-field-media-oembed-video.aspect-ratio-1-1 {
  padding-top: 100%;
}

In the media type display tab, I changed the field to use my field widget, set a reasonable max width, and enabled preserve aspect option.

A no patch solution that handles multiple video aspect ratios. Verified with youTube and Vimeo videos. This could also be expanded to handle portrait videos but I did not have that need.

imclean’s picture

Just adding some information which could be useful to this discussion.

YouTube's oEmbed response contains a width and height.

https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=nu8KX...

{
   "title":"How to load test with Goose - Part 1: Drupal 9 Umami on Pantheon with Fastly  - Tag1 Team Talk",
   "author_name":"Tag1 Consulting, Inc.",
   "author_url":"https://www.youtube.com/c/Tag1ConsultingInc",
   "type":"video",
   "height":113,
   "width":200,
   "version":"1.0",
   "provider_name":"YouTube",
   "provider_url":"https://www.youtube.com/",
   "thumbnail_height":360,
   "thumbnail_width":480,
   "thumbnail_url":"https://i.ytimg.com/vi/nu8KXNggM9s/hqdefault.jpg",
   "html":"\u003ciframe width=\u0022200\u0022 height=\u0022113\u0022 src=\u0022https://www.youtube.com/embed/nu8KXNggM9s?feature=oembed\u0022 frameborder=\u00220\u0022 allow=\u0022accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\u0022 allowfullscreen title=\u0022How to load test with Goose - Part 1: Drupal 9 Umami on Pantheon with Fastly  - Tag1 Team Talk\u0022\u003e\u003c/iframe\u003e"
}

This width and height is the minimum size required to play the video.

When submitting a request for an oEmbed resource, the maximum width and height (maxwidth, maxheight) can be sent. If the minimum response size is larger than the maximum request size then the request should fail.

Currently the the iFrame dimensions are set by the provider to exactly the minimum size. When the maximum height and/or width is entered, Drupal sets the iFrame to exactly these dimensions.

Question: Does Drupal pass along the maximum width and height settings in the request, when entered?

Sending the maxheight and maxwidth with the requests results in a response with at least one dimension matching the max and the other maintaining aspect ratio.

https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=nu8KX...

{
   "title":"How to load test with Goose - Part 1: Drupal 9 Umami on Pantheon with Fastly  - Tag1 Team Talk",
   "author_name":"Tag1 Consulting, Inc.",
   "author_url":"https://www.youtube.com/c/Tag1ConsultingInc",
   "type":"video",
   "height":563,
   "width":1000,
   "version":"1.0",
   "provider_name":"YouTube",
   "provider_url":"https://www.youtube.com/",
   "thumbnail_height":360,
   "thumbnail_width":480,
   "thumbnail_url":"https://i.ytimg.com/vi/nu8KXNggM9s/hqdefault.jpg",
   "html":"\u003ciframe width=\u00221000\u0022 height=\u0022563\u0022 src=\u0022https://www.youtube.com/embed/nu8KXNggM9s?feature=oembed\u0022 frameborder=\u00220\u0022 allow=\u0022accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\u0022 allowfullscreen title=\u0022How to load test with Goose - Part 1: Drupal 9 Umami on Pantheon with Fastly  - Tag1 Team Talk\u0022\u003e\u003c/iframe\u003e"
}

Drupal should therefore:

  1. Submit the maxwidth and maxheight parameters in the request
  2. Respect the height and width contained in the response
imclean’s picture

I've created a new issue for #51.

imclean’s picture

To correct myself:

This width and height is the minimum size required to play the video.

When submitting a request for an oEmbed resource, the maximum width and height (maxwidth, maxheight) can be sent. If the minimum response size is larger than the maximum request size then the request should fail.

This doesn't seem to be true. It's simply a default width and height, not a minimum.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

chris matthews’s picture

Priority: Normal » Major

Lots of great workarounds here, but what is the path forward for a fix in core?

chris matthews’s picture

The CSS in #27 mostly works for me, but has an issue on Bootstrap themes
I'm using:

  • Core 9.4.8
  • Bootstrap 3 8.x-3.25
  • Field Group 8.x-3.3
  • Field Formatter Class 8.x-1.5

With bootstrap themes, you can use the Field Group + Field Formatter Class modules to control the page layout by adding bootstrap .col classes to rows created with the HTML element on a Field Group. When the CSS in #27 is added, it overrides the .col classes added to the Field Group row and therefore is always displayed at full 12 column width. So, while #27 is a workaround for some themes, it doesn't work for all themes. Therefore, it seems like the proposal in #51 seems like a better path forward.

imclean’s picture

@Chris Matthews, there's an issue which deals with max_width and max_height settings and should also resolve the aspect ratio problem in most cases. #2966656: Negotiate max width/height of oEmbed assets more intelligently

xjm’s picture

Issue tags: -Needs follow-up +Needs followup
romulasry’s picture

Yeah I would love for this to be fixed.

imclean’s picture

@romulasry you can try the patch in #2966656-34: Negotiate max width/height of oEmbed assets more intelligently to see if it resolves the issue for you.

romulasry’s picture

@imclean don't have the time at the moment.

hudri’s picture

Modern browsers support the new aspect-ratio property. Example for a responsive 16:9 video iframe, with a very unobtrusive 0-0-1 CSS selector specifity:

iframe:where(.media-oembed-content) {
  display: block;
  width: 100%; 
  height: auto;
  aspect-ratio: 16 / 9;
}

#27 which still works excellent, even with less modern browsers like SafarIE (pun intended)

tormi’s picture

#27 required additional position: static; override for .contextual-region in web/themes/custom/<olivero_subtheme>/css/components/embedded-media.pcss.css when using Olivero subtheme to fix the missing video preview in node editing mode:

.field--name-field-media {
  position: relative;
  overflow: hidden;
  width: 100%;
  padding-top: 56.25%; /* 16:9 Aspect Ratio (divide 9 by 16 = 0.5625) */
  /* Fix hidden video issue in editing mode, #35. */
  .contextual-region {
    position: static;
  }
}

#62 worked flawlessly with Drupal version 10.0.7.

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

heddn’s picture

StatusFileSize
new9.85 KB

Re-roll. But I'm also testing out the css in #62.

jwilson3’s picture

When would you ever not want to maintain the intended original aspect ratio?

imclean’s picture

@jwilson3, this may change the size of embedded videos on existing sites when they upgrade.

lauriii’s picture

Issue tags: -Novice
joelpittet’s picture

I agree with @jwilson3 in #66. This should be default to always use the aspect ratio. That said, if there is no value set for this setting (on existing sites) it should remain off as mentioned in #67.

It's unfortunate that the default settings are always merged, this is why we can't have nice things *whines*.

It seems like this should be set the default for new installs to be TRUE and maybe we need an update hook to set it to FALSE for existing sites? Would that work?

imclean’s picture

A related issue which could resolve this issue has been committed to 10.3 and 11. I've added some screenshots of before and after for comparison. See #2966656-31: Negotiate max width/height of oEmbed assets more intelligently

In a nutshell: oembed providers support maintaining aspect ratio at different sizes using query parameters maxwidth and maxheight. The above issue takes this into account so the width and height of the iframes will be set correctly.

dalemoore’s picture

So is this issue considered closed and what's linked by @imclean is the solution (setting a maxwidth and maxheight manually in the field display)?

FYI, the solution in #62 should not be the solution, as this affects all oEmbed iframes. I tested it out and my Podbean oembed was sized to 16/9 so there was now a huge whitespace gap up under the podcast player. May work fine for YouTube videos that happen to be 16/9, but not all videos will always be 16/9.

handkerchief’s picture

I'm using this scss (copied from bootstrap 5):

.field--name-field-media-oembed-video {
  position: relative;
  width: 100%;
  &:before {
    display: block;
    padding-top: 56.25%; // 16x9
    content: "";
  }
  iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }
}
mortona2k’s picture

Youtube is not only 16:9, we also have shorts now.

I think we can use the height/width in the oembed response to set the aspect ratio on either the iframe or container.

I don't really think it should be a style attribute, but here is a working proof of concept:

function HOOK_preprocess_media(&$variables) {
  $iframe_attributes = &$variables['content']['field_media_oembed_video'][0]['#attributes'];
  $height = $iframe_attributes['height'];
  $width = $iframe_attributes['width'];
  $iframe_attributes['style'] = "aspect-ratio: $width / $height; height: auto;" . $iframe_attributes['style'];
}

With this, the video can grow or shrink and the height is not a fixed size. You probably want a way to select whether it's displayed as full width or not by setting width: 100%;

Out of the box, the Remote video display is set to max height/width 0, which returns the defaults from the oembed provider.

That's pretty small for youtube, so set it to the max that you would want to display for your layout.

I set it to 1200 x 600. This means I can use a regular 16x9 video that will fill my 200px main column, or a short video that is narrow and max 600px tall.

A big question is whether the height/width values are reliable from the provider. Another is how to set overrides if desired.

For other oembed content, like codepen or spotify, I'd want settings like full width, fixed height, respect aspect ratio.

I think the way to implement this is to set a variable for aspect ratio and use that in .media-oembed-content.

I was able to add those as style options on embedded media, with notes from:
https://www.drupal.org/project/drupal/issues/3406020
https://www.drupal.org/project/drupal/issues/3117172#comment-15720466

Currently we only have display modes to select these kinds of options for embedded content.

laura.gates’s picture

Just adding to the above conversation, I got around this by adding a field to media asking users to select what aspect ratio they want:

  • default 16:9
  • square 1:1
  • vertical 4:5

I then themed as normal for my different display modes.

pcambra’s picture

I've faced a somehow related issue with Floursish oEmbeds, not in terms of aspect ratio but in terms of the maxwidth/maxheight not overriding the default height and weight, for example:

https://app.flourish.studio/api/v1/oembed?url=https://public.flourish.st...

Should display a width of 960px but it shows the default 700px as it is forced by the weight attribute in the returned JSON file.

Adding a solution like #27 for the type_rich would be my suggestion to solve this.

meeni_dhobale made their first commit to this issue’s fork.

leeksoup’s picture

#27 worked great for me as well. Thank you, @mrpauldriver!

Amazing that this is still an issue in late 2025, Drupal version 10.5.6.

mayurgajar’s picture

Assigned: Unassigned » mayurgajar

mayurgajar’s picture

Assigned: mayurgajar » Unassigned
idiaz.roncero’s picture

I am also facing this problem, here is my recap of options tried and a proposal for an alternative fix.

The original problem/s

The oEmbed is "an iframe framing an iframe", so the outermost iframe should have the information about the aspect ratio returned by the provider.

In any case, the root of all problems is that this is being implemented as width and height HTML attributes, which do not work as an aspect ratio does. Also, iframes are known to need explicit heights - you can't just let width: 100% and height: auto to make them fit, as images do. In absence of a height, they will come down to a browser-defined height which usually is very small (150, see MDN)

The sum of all of this is that a 1600x900 iframe inside a 1000px wide container does not become the expected 1000x526 video but a 1000x900 one as the width decreases but the height does not.

This becomes worse as the viewport narrows and you can end up with a 300x900 unwatchable video player on mobile.

To make things worse, providers such as Youtube return by default "mininum viable" sizes, as tiny as 350x200.

Drupal Core

Core proposes to fix the "tiny sizing" issue by letting you define desired max width and heights, that are apllied both on the resource query and, in the DOM, as HTML attributes on both iframes (the oembed and the provider ones).

This fixes the tiny sizing but do not fix the aspect ratio issue.

(Also: for youtube it won't work if you just set the max-width, as it throws the error "Input value "max_height" is invalid and flag "FILTER_NULL_ON_FAILURE" was not set.")

Workaround on #27 and #50

The CSS workaround is ok and could be a minimal acceptable solution, but is not an actual fix. It will use the padding trick to set a fixed aspect ratio of 16:9, independently oif the original aspect ratio. The fix on #50 is better but depends on a shortlist of aspect ratios, while we can receive actually any possible value, so values outside the shortlist will fail to apply.

MR 13951 on #79

I have tried the MR in https://git.drupalcode.org/project/drupal/-/merge_requests/13951 and it does not fully work for me

It makes max-height optional, but the youtube video is tiny again (325x200px) and aspect ratios are not preserved.

A proposal

I think actually #73 is the best way around this, even if it implies setting inline CSS.

- It will respect any other sizing present on CSS or via width (aspect ratio does not dictate width, it will just calculate the corresponding height)
- It will accept any possible ratio that can come from the external source.
- It will be responsive out of the box and preserve the original appearance of the video, without the "black box" effect (the black bacgkround seen on the edges when the video size and frame size don't match)
- It is minimal and can be manually overriden (see next:)

To make things easily overrideable, it could be set as a CSS variable intead of direct inline css, something like this:

# Note that for aspect-ratio controlled oembeds, the height should be absent...
<iframe 
  width="1600" 
  class="media-oembed-content media-oembed-content--responsive" # We might use a class as a flag to activate this
  style="--media-oembed-aspect-ratio: 325/200"></iframe>
.media-oembed-content--responsive {
    aspect-ratio: var(--media-oembed-aspect-ratio);
}

/* Want to override it? Do it! */
.my-module-thinks-otherwise .media-oembed-content--responsive {
  --media-oembed-aspect-ratio: 1234/5678;
}

With the additional benefit that we could have, as in #27, a globally defined fallback aspect ratio of 16:9 in case anything fails:

:root {
    --media-oembed-aspect-ratio: 16/9;
}

Which, by the way, is just as easy to override if you need a different one on your theme!

/* yourtheme.css */
:root {
    --media-oembed-aspect-ratio: 33/56;
}

In the future

With modern css, aspect ratio could even be directly read from the attributes, but this needs the type(<number>) conversion from string to integer that only works for some browsers.

.media-oembed-content--responsive {
    aspect-ratio: attr(width type(<number>)) / attr(height type(<number>));
    height: auto; // Needed to unset the explicit height and let the aspect-ratio do its thing. Another solution could be to use data-attributes instead
}
idiaz.roncero’s picture

Created a new MR that implements #81 as a proof of concept.

Working correcly on my side.

Missing tests, will updated it asap but I wanted to have a POC so people can try it.

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

chris matthews’s picture

For anyone using a Bootstrap 5 theme, this works great:

.media-oembed-content {
  width: 100%;
  height: auto;
  aspect-ratio: 16 / 9;
  display: block;
}

But, it of course not a global solution for everyone.