Kotetsu Chan
Kotetsu Chan

Reputation: 95

Why is my React stylesheet media query not working?

I am connecting an external stylesheet to my React component, and I have a media query and I intend the logo to have a height of 100vh when the screen width is less than 300px. However this media query is ignored and only the original styles apply. I tried adding the css directly in the HTML file using the style tag. Here is the relevant code:

Logo.js

import React from "react";
import "./Logo.css";

export default class Logo extends React.Component {
  render() {
    return (
      <img 
        alt=""
        className="Logo"
        src="../logo.png"
      />
    );
  };  
};

Logo.css

.Logo {
  position: absolute;
  left: 42vw;
  bottom: calc(50vh + 4vw);
  height: 16vw;
};

@media screen and (max-width: 300px) {
  .Logo {
    height: 100vh;
  };
};

Upvotes: 1

Views: 2002

Answers (2)

Kotetsu Chan
Kotetsu Chan

Reputation: 95

Using hooks in react:

import React from "react";
import { useMediaQuery } from "react-responsive";

export default function Logo() {
  const isDesktop = useMediaQuery({
    query: '(min-aspect-ratio: 1/1)'
  });
  let logo = {};

  if (isDesktop) {
    logo = {
      position: "absolute",
      left: "42vw",
      bottom: "calc(50vh + 4vw)",
      height: "16vw"
    };
  } else {
    logo = {
      position: "absolute",
      left: "38vw",
      bottom: "calc(50vh + 6vw)",
      height: "24vw",
    };
  };

  return (
    <img 
      alt=""
      style={logo}
      src="../logo.png"
    />
  );
};

Remember to download useMediaQuery by typing npm install react-responsive --save into the command line.

Upvotes: 2

Ozgur Sar
Ozgur Sar

Reputation: 2214

Please try adding this to the head section of your code.

<meta name="viewport" content="width=device-width,initial-scale=1">

Upvotes: 0

Related Questions