size
size()
provides data to change the size of the floating
element. For instance, you can resize it so it doesn't overflow
the available space:
If your floating element's content cannot be resized such as in
the example, you can make the floating element scrollable with
overflow: scroll
(or auto
).
Usage
import {computePosition, size} from '@floating-ui/dom';
computePosition(referenceEl, floatingEl, {
middleware: [
size({
apply({width, height, reference, floating}) {
// Do things with the data, e.g.
Object.assign(floatingEl.style, {
maxWidth: `${width}px`,
maxHeight: `${height}px`,
});
},
}),
],
});
If your element has a border, ensure your CSS is using
box-sizing: border-box
.
Options
These are the options you can pass to size()
.
interface Options extends DetectOverflowOptions {
apply?: (args: Dimensions & ElementRects) => void;
}
apply
default: undefined
Unlike other middleware, in which you assign styles after
computePosition()
has done its work, size()
has its
own apply
function to do the work during the
lifecycle:
size({
apply({width, height}) {
// Style mutations here
},
});
This is because the x
and y
coordinates become incorrect
after you've changed the size, and so changes to the dimensions
of the floating element need to be performed before the
coordinates get assigned to it.
...detectOverflowOptions
All of detectOverflow's options can be passed. For instance:
size({padding: 5}); // 0 by default
Using with flip
Using size()
together with flip()
enables some
useful behavior. The floating element can be resized, thus
allowing it to prefer its initial placement as much as possible,
until it reaches a minimum size, at which point it will flip.
If you're using the padding
option in either
middleware, ensure they share the same value.
bestFit
The 'bestFit'
fallback strategy in the flip()
middleware is the default, which ensures the best fitting
placement is used. In this scenario, place size()
after flip()
:
const middleware = [
flip(),
size({
apply({width, height}) {
// ...
},
}),
];
This strategy ensures the floating element stays in view at all times at the most optimal size.
initialPlacement
If instead, you want the initial placement to take precedence,
and are setting a minimum acceptable size, place size()
before flip()
:
const middleware = [
size({
apply({width, height}) {
Object.assign(floatingEl.style, {
// Minimum acceptable height is 50px.
// `flip` will then take over.
maxHeight: `${Math.max(50, height)}px`,
});
},
}),
flip({
fallbackStrategy: 'initialPlacement',
}),
];
Match reference width
A common feature of select dropdowns is that the dropdown matches
the width of the reference regardless of its contents. You can
also use size()
for this, as the Rect
s get
passed in:
size({
apply({reference}) {
Object.assign(floatingEl.style, {
width: `${reference.width}px`,
});
},
});