首页 > 解决方案 > 如何使选择列表出现在另一个元素上?

问题描述

我正在基于这个React Template构建一个项目。
在其中一个组件中,我有一个选择列表,在它下面有一个卡片元素。
问题是当我单击列表时,项目出现在卡片元素下,如下所示:

在此处输入图像描述

我有一种感觉,这是由模板本身的 CSS 代码造成的,该代码将卡片配置为出现在所有其他元素之上。

所以我所做的是我创建了一个新的反应项目:

npx 创建反应应用程序

我的怀疑是对的。
我复制了基本相同的代码:

const selectStyles = {
  control: (styles) => ({ ...styles, backgroundColor: "white" }),
  option: (styles) => {
    return {
      ...styles,
      backgroundColor: "green",
    
      "z-index": -5,
    };
  },
};

export default class App extends Component {
  render() {
    return (
      <Fragment>
        <Select
          className="basic-single"
          classNamePrefix="select"
          defaultValue={colourOptions[0]}
          name="color"
          options={colourOptions}
          styles={selectStyles}
        />
        <Card
          style={{
            position: "absolute",
            "background-color": "red",
            "z-index": 5,
          }}
        >
          <CardImg
            top
            width="100%"
            src="/assets/318x180.svg"
            alt="Card image cap"
          />
          <CardBody>
            <CardTitle tag="h5">Card title</CardTitle>
            <CardSubtitle tag="h6" className="mb-2 text-muted">
              Card subtitle
            </CardSubtitle>
            <CardText>
              Some quick example text to build on the card title and make up the
              bulk of the card's content.
            </CardText>
            <Button>Button</Button>
          </CardBody>
        </Card>
      </Fragment>
    );
  }
}

选择的项目出现在卡片上方:
在此处输入图像描述

这张卡片是红色的。

结论:问题是由模板的卡片css代码引起的。

如您所见,我尝试使用z-index属性的不同配置,但无济于事。

知道如何解决这个问题吗?

标签: htmlcssbootstrap-4z-indexreactstrap

解决方案


问题在于 z-index 和位置,无论您想在顶部显示哪个内容,都应该具有更高的 z-index 值。

  • 尝试为选择下拉菜单提供与卡片相比较高的值。
  • 如果不需要,请尝试删除两个 CSS 属性 position: absolute 和 z-index。绝对位置仅在需要将内容移动到相应相对父容器的任何位置时使用。因此,如果您只是在练习而不是在进行设计,请尝试将两者都删除。

推荐阅读