React-bootstrap 如何水平居中一个元素只考虑它的父元素

React-bootstrap how to horizontally center an element only taking account of it's parent

您好,我正在使用 react-bootstrap 库。我想将导航栏上的搜索栏和按钮居中。但是在居中的同时,它也考虑到了兄弟元素(标志)并向页面右侧倾斜。如果可能的话,我不想通过施加蛮力减去 margin-left 来解决这个问题。我对这些证明内容的东西感到困惑。提前致谢。

<Navbar style={{ backgroundColor: "#D3D3D3" }}>
  <Nav className="d-flex justify-content-start">
    <NavbarBrand href="/">
      <img src={logo} alt="pokedex-logo" style={{ width: 250, marginLeft: 20 }} />
    </NavbarBrand>
  </Nav>
  <Nav className="d-flex flex-grow-1 justify-content-center">
    <Form className="d-inline-flex">
      <FormControl
        type="search"
        placeholder="Type pokemon name"
        value={search}
        onChange={e => setSearch(e.target.value)}
      />
      <Button
        style={{ backgroundColor: "#ffe031", color: "#396bba" }}
        onClick={() => history.push(`/pokemon/${search}`)}
      >
        <strong>Search</strong>
      </Button>
    </Form>
  </Nav>
</Navbar>

这样试试:

<Navbar style={{ backgroundColor: "#D3D3D3", display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'start' }}>
    <NavbarBrand href="/">
        <img src={logo} alt="pokedex-logo" style={{ width: 250 }} />
    </NavbarBrand>
    <Form className="" style={{ margin: 'auto' }}>
        <FormControl type="search" placeholder="Type pokemon name" value={search} onChange={e => setSearch(e.target.value)}/>
        <Button style={{ backgroundColor: "#ffe031", color: "#396bba" }} onClick={() => history.push(`/pokemon/${search}`)}>
            <strong>Search</strong>
        </Button>
    </Form>
</Navbar>

此处,Navbar 具有显示弹性且弹性方向为行,因此徽标和 2 个搜索元素(文本字段和搜索按钮)将显示在一行中.然后 alignItems:'center' 将这 3 个元素 在导航栏中垂直 居中,然后 justifyContent: 'start' 将这 3 个元素 水平[=31] 移动到导航栏的开头=]. 在此之后,为了使搜索的 2 个元素居中,在 Form.

中使用 margin:'auto'

还有另一种方法:(如果上面的代码没有正确地将搜索元素居中对齐)

<Navbar style={{ position: 'relative', display: 'flex', backgroundColor: "#D3D3D3" }}>
    <NavbarBrand href="/" style={{float: 'left'}}>
        <img src={logo} alt="pokedex-logo" style={{ width: 250 }} />
    </NavbarBrand>
    <Form style={{ float: 'none', position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}>
        <FormControl type="search" placeholder="Type pokemon name" value={search} onChange={e => setSearch(e.target.value)} />
        <Button style={{ backgroundColor: "#ffe031", color: "#396bba" }} onClick={() => history.push(`/pokemon/${search}`)}>
            <strong>Search</strong>
        </Button>
    </Form>
</Navbar>

在此代码中,使用了 position 和 float 的 CSS 属性。 float: 'left' 将徽标向左移动,搜索元素有 float: 'none'。搜索元素使用位置 属性 与导航栏的中心对齐,该导航栏具有 position: 'relative'.