Search code examples
reactjsinputchakra-ui

Aligning InputLeftElement with Input in Chakra-ui


I'm trying to align <LeftInputElement> with the baseline or center of <Input>. The problem is that I'm using fontSize="2xl" and the elements end up misaligned.

Here's the code:

<HStack>
    <Text fontSize={"2xl"}>{recordName ? recordName : "Record"}:</Text>
    <InputGroup
      width="25%"
      padding={5}
      fontSize={"2xl"}
    >
      <InputLeftElement
        children={<Text fontSize={"2xl"}>{prefix}</Text>}
      />
      <Input
        variant="field"
        fontSize={"2xl"}
        borderRadius={20}
        placeholder="enter value"
      />
    </InputGroup>
    <Button fontSize={"2xl"}>
      <BsSearch />
      &nbsp; Find Record
    </Button>
  </HStack>

No matter what I do (display='flex', alignContent='center', alignItems='center', alignSelf='center') - not all at once and where applicable, of course, I end up with `InputLeftElement` having top aligned to the container and everything else is aligned correctly.

How do I keep InputLeftElement aligned and displaying inside the Input element?


Solution

  • The InputLeftElement is absolute positioned to the top left of the InputGroup component, so it isn't going to take into account changes to the InputGroup component's padding. Adjust the InputLeftElement margin to account for the padding added to the InputGroup.

    <HStack>
        <Text fontSize={"2xl"}>{recordName ? recordName : "Record"}:</Text>
        <InputGroup
          width="25%"
          padding={5}
          fontSize={"2xl"}
        >
          <InputLeftElement
            margin={5}
            children={<Text fontSize={"2xl"}>{prefix}</Text>}
          />
          <Input
            variant="field"
            fontSize={"2xl"}
            borderRadius={20}
            placeholder="enter value"
          />
        </InputGroup>
        <Button fontSize={"2xl"}>
          <BsSearch />
          &nbsp; Find Record
        </Button>
      </HStack>
    

    Chakra playground showing solution