使所有项目与水平滚动适合div

时间:2019-06-07 13:26:34

标签: css reactjs

我想将所有具有其原始大小的项目放入固定宽度的容器中。我不想牺牲孩子的宽度以适合放入容器。我想要水平滚动。

我已经尝试过flexbox使它们全部内联,但是我不确定如何添加水平滚动条。

我想使用滚动条一次显示5个块。

这就是现在的样子。

enter image description here

import styled from 'styled-components';

const Block = styled.div`
    height: 300px;
    width: 200px;
    border: 2px solid black;
`;

const Container = styled.div`
    display: flex;
overflow-x: scroll;
`;

const Planner = () => (
    <Container>
        <Block>Block 1</Block>
        <Block>Block 2</Block>
        <Block>Block 3</Block>
        <Block>Block 4</Block>
        <Block>Block 5</Block>
        <Block>Block 6</Block>
        <Block>Block 7</Block>
        <Block>Block 8</Block>
        <Block>Block 9</Block>
        <Block>Block 10</Block>
        <Block>Block 11</Block>
    </Container>
);

export default Planner;

3 个答案:

答案 0 :(得分:2)

此处的关键方面是删除项目的宽度,而是像这样设置flex属性:flex: 0 0 200px。这样可以确保这些项目既不会增长,前一个0也不会缩小,第二个0也不会缩小,并且宽度为200像素。

然后确保您的容器隐藏了溢出的内容。

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";

const Block = styled.div`
  height: 300px;
  flex: 0 0 200px;
  border: 2px solid black;
`;

const Container = styled.div`
  display: flex;
  overflow-x: auto;
`;

const Planner = () => (
  <Container>
    <Block>Block 1</Block>
    <Block>Block 2</Block>
    <Block>Block 3</Block>
    <Block>Block 4</Block>
    <Block>Block 5</Block>
    <Block>Block 6</Block>
    <Block>Block 7</Block>
    <Block>Block 8</Block>
    <Block>Block 9</Block>
    <Block>Block 10</Block>
    <Block>Block 11</Block>
  </Container>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<Planner />, rootElement);

答案 1 :(得分:0)

尝试将其添加到您的Block组件的css:display: inline-block;中,然后从容器中移除flex。

答案 2 :(得分:0)

这是答案。

import styled from 'styled-components';

const Block = styled.div`
    height: 300px;
    min-width: 200px;
    border: 2px solid black;
`;

const Container = styled.div`
    display: flex;
    overflow: auto;
`;

const Planner = () => (
    <Container>
        <Block>Block 1</Block>
        <Block>Block 2</Block>
        <Block>Block 3</Block>
        <Block>Block 4</Block>
        <Block>Block 5</Block>
        <Block>Block 6</Block>
        <Block>Block 7</Block>
        <Block>Block 8</Block>
        <Block>Block 9</Block>
        <Block>Block 10</Block>
        <Block>Block 11</Block>
    </Container>
);

export default Planner;