I want to know the margin-left of div1, so I can use it in my code. Setting it this way, the margin on the left will change depending on the screen size. How can I detect the margin left of this div?
<div class="max-w-6xl m-auto">
</div>
I want to know the margin-left of div1, so I can use it in my code. Setting it this way, the margin on the left will change depending on the screen size. How can I detect the margin left of this div?
<div class="max-w-6xl m-auto">
</div>
In react, you can make use of the ref callback, which receives the HTML DOM element as an argument. Inside of this callback, you could query the margin-left style from the element and store it in a state. Here's an example:
const App = () => {
const [marginLeft, setMarginLeft] = useState(0); // in pixels
const retrieveMargin = (elm) => {
if (elm != null) {
let styles = window.getComputedStyle(elm);
let ml = styles.getPropertyValue("margin-left");
setMarginLeft(Number.parseInt(ml.replace("px", "")));
}
};
return <div class="mydiv" ref={retrieveMargin}></div>;
};