Class AspectRatio


public class AspectRatio extends StyledElement<AspectRatio>
A container that maintains a specific aspect ratio regardless of content.

AspectRatio uses the CSS aspect-ratio property to ensure the container maintains its proportions as it scales. This is useful for images, videos, maps, and other media that should maintain their aspect ratio to prevent layout shifts.

Common Ratios:

Usage:


 // Video container with 16:9 ratio
 AspectRatio videoWrapper = new AspectRatio(AspectRatio.Ratio.VIDEO);
 videoWrapper.addElement(videoPlayer);

 // Square thumbnail
 AspectRatio thumbnail = new AspectRatio(AspectRatio.Ratio.SQUARE);
 thumbnail.addElement(image);

 // Custom ratio (e.g., 2:1)
 AspectRatio banner = new AspectRatio(2, 1);
 banner.addElement(bannerImage);

 // Wrap existing element
 AspectRatio wrapped = new AspectRatio(Ratio.PHOTO, existingImage);
 
Since:
2025
Version:
1.0
Author:
Marvin P. Warble Jr.
See Also:
  • Constructor Details

    • AspectRatio

      public AspectRatio()
      Constructs an aspect ratio container with a 16:9 (video) ratio.
    • AspectRatio

      public AspectRatio(AspectRatio.Ratio ratio)
      Constructs an aspect ratio container with the specified ratio preset.
      Parameters:
      ratio - the aspect ratio preset
    • AspectRatio

      public AspectRatio(int width, int height)
      Constructs an aspect ratio container with a custom ratio.
      Parameters:
      width - the width component of the ratio
      height - the height component of the ratio
    • AspectRatio

      public AspectRatio(AspectRatio.Ratio ratio, Element<?> content)
      Constructs an aspect ratio container with content.
      Parameters:
      ratio - the aspect ratio preset
      content - the element to contain
    • AspectRatio

      public AspectRatio(int width, int height, Element<?> content)
      Constructs an aspect ratio container with custom ratio and content.
      Parameters:
      width - the width component of the ratio
      height - the height component of the ratio
      content - the element to contain
  • Method Details

    • setRatio

      public AspectRatio setRatio(AspectRatio.Ratio ratio)
      Sets the aspect ratio using a preset.
      Parameters:
      ratio - the aspect ratio preset
      Returns:
      this AspectRatio for method chaining
    • setRatio

      public AspectRatio setRatio(int width, int height)
      Sets a custom aspect ratio.
      Parameters:
      width - the width component of the ratio
      height - the height component of the ratio
      Returns:
      this AspectRatio for method chaining
    • setRatio

      public AspectRatio setRatio(double ratio)
      Sets the aspect ratio using a decimal value.

      For example, 1.777 for 16:9, 1.333 for 4:3.

      Parameters:
      ratio - the aspect ratio as a decimal (width / height)
      Returns:
      this AspectRatio for method chaining