๐Ÿš€ Handling Browser-Specific CSS with a Utility Function

Different browsers apply CSS differently, which can lead to inconsistencies in UI. To tackle this, I created a utility function that detects the userโ€™s browser (Firefox, Safari, Edge, etc.) and applies the appropriate styles dynamically.

Code Implementation:

export const getBrowserCssFix = (key: string): string | null => {
  const userAgent = navigator.userAgent.toLowerCase();

  let browserType: string;

  switch (true) {
    case userAgent.includes("firefox"):
      browserType = "firefox";
      break;
    case /^((?!chrome|android).)*safari/i.test(navigator.userAgent):
      browserType = "safari";
      break;
    case userAgent.includes("edg"):
      browserType = "edge";
      break;
    default:
      browserType = "default";
  }

  switch (key) {
    case "scroll":
      switch (browserType) {
        case "firefox":
          return "firefoxScroll";
        case "safari":
          return "safariScroll";
        case "edge":
          return "edgeScroll";
        default:
          return "defaultScroll";
      }

    case "tableBorder":
      switch (browserType) {
        case "firefox":
          return "border border-primary_text";
        case "safari":
          return "border border-safari";
        case "edge":
          return "border border-edge";
        default:
          return "border border-y-0";
      }

    default:
      return null;
  }
};

How It Works:

:heavy_check_mark: Detects the browser using navigator.userAgent
:heavy_check_mark: Uses switch statements for clean and structured logic
:heavy_check_mark: Returns browser-specific CSS classes for consistent UI

Example Usage:

getBrowserCssFix("scroll"); // Returns scroll styles based on browser  
getBrowserCssFix("tableBorder"); // Applies correct table border styles  

This approach helps maintain a smooth and consistent UI across different browsers. Let me know your thoughts or improvements! :fire::rocket:

8 Likes

Is it only suitable for typescript @pavitra.kini ?

No @aishwarya , we can use it for JavaScript as well. The function I mentioned is in TypeScript, but for JavaScript, we just need to change the prop types and use it.

2 Likes