如何使Tailwind.css响应?

时间:2020-07-12 15:59:44

标签: css reactjs tailwind-css

我有两个组成部分。在第一个MovieItem.js中,我创建了一张卡;在第二个Movies.js中,我遍历了一系列卡并在UI中显示它们-每行4个。我正在使用Tailwind网格模板列来做这样,就可以了。

 return (
    <div className="grid grid-cols-4 gap-4">
      {movies.map((movie) => (
        <MovieItem key={movie.id} movie={movie}></MovieItem>
      ))}
    </div>
  );

但是,如果屏幕的宽度小于640像素,我希望每行仅显示一张卡,这意味着每张卡的宽度应为100%,并且它们应该水平堆叠在一起,但是我对此没有任何结果。

return (
    <div className="grid grid-cols-4 sm:grid grid-cols-1 gap-4">
      {movies.map((movie) => (
        <MovieItem key={movie.id} movie={movie}></MovieItem>
      ))}
    </div>
  );

MovieItem.js

import React from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import AlternativeImage from "./AlternativeImage";

const MovieItem = ({ movie: { id, title, poster_path } }) => {
  return (
    <div className=" bg-gray-900 px-4 pt-4 pb-5 overflow-hidden rounded ">
      {poster_path ? (
        <img
          src={"https://image.tmdb.org/t/p/w400/" + poster_path}
          alt=""
          className="w-full block content-center p-4 content-image"
        />
      ) : (
        <AlternativeImage></AlternativeImage>
      )}
      <h6 className="text-base text-center text-white my-3 font-mono">
        {title}
      </h6>
      <div className="button-container">
        <Link
          to={`/movie/${id}`}
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded "
        >
          Movie Details
        </Link>
      </div>
    </div>
  );
};

export default MovieItem;

Movies.js

import React, { useContext } from "react";
import MovieItem from "./MovieItem";

import MovieContext from "../context/movie/movieContext";

const Movies = () => {
  const movieContext = useContext(MovieContext);
  const { movies } = movieContext;

  return (
    <div className="grid grid-cols-4 sm:grid grid-cols-1 gap-4">
      {movies.map((movie) => (
        <MovieItem key={movie.id} movie={movie}></MovieItem>
      ))}
    </div>
  );
};

export default Movies;

我还对Tailwind配置文件进行了必要的更改:

const tailwindcss = require("tailwindcss");
module.exports = {
  theme: {
    screens: {
      xl: { max: "1279px" },
      // => @media (max-width: 1279px) { ... }

      lg: { max: "1023px" },
      // => @media (max-width: 1023px) { ... }

      md: { max: "767px" },
      // => @media (max-width: 767px) { ... }

      sm: { max: "639px" },
      // => @media (max-width: 639px) { ... }
    },
  },
  plugins: [tailwindcss("./tailwind.js"), require("autoprefixer")],
};

enter image description here

1 个答案:

答案 0 :(得分:0)

默认情况下,Tailwind使用移动式第一个断点系统,类似于在Bootstrap或Foundation中可能使用的系统。

这意味着未加前缀的实用程序(例如大写)在所有屏幕尺寸上都有效,而带前缀的实用程序(例如md:uppercase)仅在指定的断点及更高的断点处生效。

您的情况就是这样

grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2 md:gap-4

选中docs