Element size

2 snippets across 2 stacks - HTML & CSS, React

HCHTML & CSS

Width & Height

HC · Box Model
Syntax
width: value; height: value;
min-width | max-width | min-height | max-height
Example
.container {
  width: 100%;
  max-width: 1200px;
}

.sidebar {
  width: 280px;
  min-height: 100vh;
}

.avatar {
  width: 48px;
  height: 48px;
  aspect-ratio: 1;
}

Note Avoid setting fixed heights on text containers since content length varies. Use min-height instead. The aspect-ratio property maintains proportions without needing both width and height.

REReact

Callback Refs

RE · useRef
Syntax
<element ref={(node) => {
  // node is the DOM element or null on unmount
}} />
Example
function MeasuredBox() {
  const [height, setHeight] = useState(0);

  const measureRef = (node) => {
    if (node !== null) {
      setHeight(node.getBoundingClientRect().height);
    }
  };

  return (
    <div>
      <div ref={measureRef} style={{ padding: '20px' }}>
        <p>This box has dynamic content.</p>
        <p>Its height is measured via a callback ref.</p>
      </div>
      <p>Measured height: {height}px</p>
    </div>
  );
}

Note Callback refs fire whenever the ref attaches or detaches. In React 19, callback refs can return a cleanup function that runs when the element is removed, similar to useEffect cleanup. Useful for measuring elements or integrating third-party DOM libraries.

Frequently asked questions

How does HTML & CSS handle element size?
This task is covered in 2 stacks on this page: HTML & CSS, React. The "Width & Height" snippet in HTML & CSS uses `width: value; height: value;`.
Which code does the HTML & CSS example use?
The "Width & Height" snippet uses `width: value; height: value;`, from the Box Model section of the HTML & CSS cheat sheet.
Which stacks cover "element size" on this page?
HTML & CSS, React. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Width & Height": Avoid setting fixed heights on text containers since content length varies. Use min-height instead. The aspect-ratio property maintains proportions without needing both width and height.