diff --git a/.changeset/fix-objectfit-css-override.md b/.changeset/fix-objectfit-css-override.md new file mode 100644 index 00000000..6bd04e47 --- /dev/null +++ b/.changeset/fix-objectfit-css-override.md @@ -0,0 +1,5 @@ +--- +"@unpic/core": patch +--- + +Only apply default `object-fit: cover` when no CSS class is provided, allowing CSS classes to control the property diff --git a/packages/core/src/base.ts b/packages/core/src/base.ts index c648f0d2..a436aca4 100644 --- a/packages/core/src/base.ts +++ b/packages/core/src/base.ts @@ -56,7 +56,7 @@ export const getStyle = < height, aspectRatio, layout, - objectFit = "cover", + objectFit, background, }: Pick< UnpicBaseImageProps, @@ -324,6 +324,15 @@ export function transformBaseImageProps< options, ...transformedProps } = transformSharedProps(props); + + // Default to object-fit: cover only if no class is provided + // This allows CSS classes to control object-fit without being overridden + const hasClass = + "class" in transformedProps || "className" in transformedProps; + if (objectFit === undefined && !hasClass) { + objectFit = "cover"; + } + // Auto-generate a low-res image for blurred placeholders if (transformer && background === "auto") { const lowResHeight = aspectRatio diff --git a/packages/core/test/core.test.tsx b/packages/core/test/core.test.tsx index 2462b085..772f7b00 100644 --- a/packages/core/test/core.test.tsx +++ b/packages/core/test/core.test.tsx @@ -50,4 +50,56 @@ describe("Core", () => { expect(props.width).toEqual(100); expect(props.height).toEqual(200); }); + + test("defaults to object-fit: cover when no class is provided", () => { + const props = transformProps({ + src: "https://res.cloudinary.com/example/image/upload/images/my-image", + width: 800, + height: 600, + layout: "constrained", + }); + expect((props.style as Record)["object-fit"]).toEqual( + "cover", + ); + }); + + test("does not apply object-fit when class is provided", () => { + const props = transformProps({ + src: "https://res.cloudinary.com/example/image/upload/images/my-image", + width: 800, + height: 600, + layout: "constrained", + class: "my-custom-class", + } as any); + expect( + (props.style as Record)["object-fit"], + ).toBeUndefined(); + }); + + test("does not apply object-fit when className is provided", () => { + const props = transformProps({ + src: "https://res.cloudinary.com/example/image/upload/images/my-image", + width: 800, + height: 600, + layout: "constrained", + className: "my-custom-class", + } as any); + expect( + (props.style as Record)["object-fit"], + ).toBeUndefined(); + }); + + test("applies explicit objectFit even when class is provided", () => { + const props = transformProps({ + src: "https://res.cloudinary.com/example/image/upload/images/my-image", + width: 800, + height: 600, + layout: "constrained", + class: "my-custom-class", + objectFit: "contain", + } as any); + expect((props.style as Record)["object-fit"]).toEqual( + "contain", + ); + }); });