Resize any DOM element using two lines of CSS
I recently came across this video by Kamran Ahmed, where he demonstrates how to resize any DOM element using just two lines of CSS. And I was like, “What the heck, how did I not know about this all this time?”
So, to make any DOM element resizable, you can add the following CSS to it.
div {
resize: auto;
overflow: auto;
}
The resize
property allows you to specify whether an element is resizable by the user, and the overflow
property ensures that content within the element can be scrolled if it exceeds the size of the element.
Here’s a CodePen to see it in action. Try resizing the boxes by dragging the bottom right corner.
See the Pen Wiggly hover animation by Amit Merchant (@amit_merchant) on CodePen.
You can also limit the resizing to specific directions by using values like horizontal
, vertical
, or both
. For example, if you want to allow resizing only horizontally, you can use:
div {
resize: horizontal;
overflow: auto;
}
And that’s it! I think this is a neat little trick that can be useful in various scenarios, especially when building user interfaces where you want to give users the ability to adjust the size of certain elements dynamically.
This is also helpful when you want to validate the resizing behavior of certain elements during development without tinkering too much with width and height properties.
👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!