I am currently dealing with an input component that adjusts its size based on the maxWidth property and can also shrink when the screen size changes.
The issue I'm facing is that the margin doesn't stay consistent when set to a specific maxWidth in pixels, but works fine when the input is set to 100%. Additionally, centering the input creates padding problems, which seem to stem from the same underlying issue.
How can I limit the max-width of the input while accounting for paddings and maintaining flexibility to allow it to shrink?
https://i.sstatic.net/ygFfr.png
Check out the Codesandbox (you can fork it and make changes).
import * as React from "react";
import styled from "styled-components";
interface Props extends React.ComponentPropsWithoutRef<"input"> {
maxWidth?: string;
}
const Input = React.forwardRef<HTMLInputElement, Props>((props, ref) => {
return <StyledInput ref={ref} {...props} />;
});
const defPadding = 5;
const StyledInput = styled.input<Props>`
box-sizing: content-box;
margin: 5px;
vertical-align: middle;
padding: ${defPadding}px 0;
box-shadow: inset 0 0 0 1px blue;
border-radius: 5px;
border: none;
outline: none;
font: inherit;
max-width: calc(
${({ maxWidth }): string => maxWidth || "100%"} - ${defPadding * 2}px
);
width: 100%;
text-align: center;
`;
export default function App() {
return (
<div className="App">
<div>
<Input />
<Input maxWidth="1000px" />
</div>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center"
}}
>
<Input />
<Input maxWidth="1000px" />
</div>
</div>
);
}