DEV Community

MINYEONG KIM
MINYEONG KIM

Posted on

Chrome Extension for CSS Layouts: HTML Visualization

Image description

When working with layouts in CSS, aligning items within a box is crucial. For those just starting with CSS, understanding how items align can be challenging at first glance. During my mentoring sessions, I always recommended my students to visually draw lines for better clarity whenever they felt confused. To make this process easier, I developed a Chrome extension, moving away from the need to define such lines directly in CSS.

Image description

The concept of using this tool is straightforward. By clicking "Add Depth", you can see a border with a random color around your elements. Additionally, you have the flexibility to change the color, line style, and width size.

The structure of the source is user-friendly. You can set the details of the lines on the popup side, which then applies to the content.

On the content side, the extension checks all depth levels from the document and applies a border style that matches the data selected by the user.

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.depthSettings) {
    applyDepthStyles(request.depthSettings);
  }
});

function applyDepthStyles(settings) {
  document.querySelectorAll("*").forEach((element) => {
    const depth = getElementDepth(element);
    const setting = settings[depth];
    if (setting) {
      element.style.border = `${setting.width}px ${setting.style} ${setting.color}`;
    } else {
      element.style.border = "";
    }
  });
}

function getElementDepth(element) {
  let depth = 0;
  while (element.parentElement) {
    depth++;
    element = element.parentElement;
  }
  return depth;
}
Enter fullscreen mode Exit fullscreen mode

You can view all the source code on github

The extension is currently under review for launch on the Chrome Store.

Top comments (0)