1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】Chakra-UIのGridで要素の位置を揃える

Last updated at Posted at 2023-06-20

はじめに

ヘッダーに配置した文字列と、コンテンツに配置した要素の位置を揃えたいです。

これを

image.png

こうしたい

image.png

flexではなくgridを使う

修正前のコード

  return (
    <Box bg="#95BFEA" height="50px" display="flex" alignItems="center">
        <Flex align="center" justify="space-between" width="100%" marginX="auto">
        <Text textAlign="center" flex="1">{title}</Text>
        {showSettingIcon && <Icon mr="4px" as={SettingsIcon} boxSize={6} />}
        </Flex>
    </Box>
  )

文字列とアイコンをflexで横並びにしているだけです。
この状態で文字列を中央寄せにしても、
画面の横幅からアイコンを除いたスペースに対して中央寄せになるので、コンテンツの文字列やアイコンと位置がずれてしまいます。

そのため、flexではなくgridを用いて文字列やアイコンの配置を細かく決めてあげます。

  • Gridタグで全体のサイズを指定
  • gridに割り当てる要素はGridItemタグで囲み、割り当てる縦横のスペースをrowSpan/colSpanで指定

今回は全体のサイズを12にし、
左配置用のアイコン:文字列:右配置用のアイコンを4:4:4で割り当てます。

修正後のコード

(戻るアイコンやメールアイコンなども追加していますが、気にしないでください)

  return (
    <Box bg="#95BFEA" height="50px" display="flex" alignItems="center">
      <Grid
        w='100%'
        templateColumns='repeat(12, 1fr)'
        gap={4}
      >
        <GridItem rowSpan={1} colSpan={4} >
          {showBackIcon && <Icon as={ArrowBackIcon} boxSize={6} onClick={handleBackIconClick} />}
        </GridItem>
        <GridItem colSpan={4} >
          <Text textAlign="center" >{title}</Text>
        </GridItem>
        <GridItem colSpan={4} >
        <Box w="100%" display="flex" justifyContent="end">
          {showSettingIcon && <Icon mr="4px" as={SettingsIcon} boxSize={6} />}
          {showEmailIcon && <Icon mr="4px" as={EmailIcon} boxSize={6} onClick={handleEmailIconClick}/>}
          </Box>
        </GridItem>
      </Grid>
    </Box>
  )

よしなにできました!

image.png

おわりに

かゆいところに手が届くと気持ちがいいです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?