Adjustable input field spacing

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>
  );
}

Answer №1

It appears that the main issue at hand pertains not to paddings, but rather the 5-pixel side margins.

To address this, you can make slight adjustments to the styles so that

<Input maxWidth="1000px" />
expands as much as possible without exceeding 1000px. The final CSS outcome should be:

width: 1000px;
max-width: calc(100% - 10px);

In your component's styles, consider implementing the following:

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(100% - ${defPadding * 2}px);
  width: ${({ maxWidth }): string => maxWidth || "auto"};
  text-align: center;
`;

If your aim is to utilize the margin: 5px, perhaps it would be beneficial to incorporate the defPadding variable in this section as well.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Formatting an HTML table for mobile devices

Hi everyone, I'm struggling to understand why my table is displaying incorrectly when switching to the mobile version. I've attempted various CSS adjustments to correct it, but the issue persists when viewed on mobile devices. Mobile view of the ...

IIS Alert: Missing Images, CSS, and Scripts!

When I tried to publish my website using IIS, I encountered the error message Cannot read configuration file due to insufficient permissions. After attempting to add permissions for IIS_USRS and realizing that this user does not exist on my computer runnin ...

Changing the background color of Material UI MobileStepper

Would appreciate some help. I am currently using the MobileStepper component, specifically: https://mui.com/api/mobile-stepper/ I am trying to set a different background color for this stepper. Upon inspecting the Dev Tools for this component, I discover ...

The Battle of Naming Styles in HTML and CSS: CamelCase versus Underscores

After reading numerous articles discussing the pros and cons of camelCase and Underscore naming conventions, I have always leaned towards camelCase due to its byte-saving nature. However, upon discovering BEM, I must admit that I am now in a state of conf ...

The scroll-to-top feature fails to function properly within the framework of Bootstrap 4

I have encountered an issue with adding a scroll to top script to my website developed using Bootstrap 4. Strangely, the script works perfectly fine on another website built with Bootstrap 3. It seems like there might be an error related to the bootstrap v ...

The radio button becomes unchecked when moving to the next fieldset

While developing a dynamic page using PHP and Laravel, I encountered a situation where I needed to add an additional radio button option to each card. Below is the code snippet for the card in question: <div class="card" style="margin:10p ...

Issues with inconsistent behavior of the select option in a form

Having some trouble with my form code. When I checked the web page, there seems to be an extra element that shouldn't be there. You can view the webpage https://i.sstatic.net/pu4ef.jpg. Inspecting it in browser developer mode, I found this extra eleme ...

scroll smoothly to a specified vertical position on a webpage using jquery animation

Hello everyone, I am relatively new to JS and currently working on creating a vertical image scroller. I have successfully implemented code to scroll from left to right on LI elements until the center of that LI is reached. However, I now want to apply thi ...

What is the best method for automatically closing the modal window?

I implemented a modal window on my website. Within the modal, there is a green button labeled "Visit" which triggers the "Bootstrap Tour". I aim for the modal to automatically close when the tour starts. To access this feature on my site, users need to ...

Automatically generate a new model instance in Django

Currently, I am working on a project that involves using django along with react.js. One of the features I have implemented is social authentication for Google using Django social auth. Everything seems to be functioning correctly as I can obtain the Djang ...

Creating a popup with multiple tabs using CSS

Struggling to navigate through the intricacies of these code snippets <!DOCTYPE html> <html lang ="en"> <head> <style type="text/css"> a{ text-decoration:none; color:#333; } #pop{ width:557px; height:400px; background:#333; ...

JavaScript Date Validation: Ensuring Proper Dates

I am working with a date string that is in the format of "DD-MM-YYYY" and have successfully validated it using this code: var dateFormat = /(0[1-9]|[12][0-9]|3[01])-(0[1-9]|1[012])-\d{4}/ ; if(!startDate.match(dateFormat)){ alert("'Start Dat ...

What is the best way to transform SASS into CSS?

Looking for an online tool to easily convert a few lines of SASS into pure CSS. Despite searching on Google, all the links I found talk about converting CSS to SASS. Below are the specific lines I need assistance in converting to CSS: =text-shadow($color ...

Dealing with the "window is not defined" error in NextJS even after incorporating useEffect

I'm facing a challenge integrating a JS library into my NextJS app. Despite using it within a useEffect hook and adding a condition to check the window object, I keep encountering an error on the server-side: ReferenceError: window is not defined Thi ...

Tips for sending multiple Formdata in a single array to an express backend

How can I efficiently send multiple form data as an array to my express backend? When I try creating an array of formData, I end up receiving an empty object in Express. Even the payload in the network tab appears empty. let arr1 = {data: []} let data1 = ...

Leveraging window.location during the registration of a user account in a React application

Here is my method for registering a user: register = event => { console.log(this.state.credentials); fetch('http://api.herokuapp.com/account/users/', { method: 'POST', headers: { 'Content ...

Why isn't my API's JSON Response showing up in PHP?

Having trouble displaying the JSON response from an API call in PHP. Despite confirming that the server, IP settings, and API status are all fine on the provider's end, I am unable to identify the problem. This is how I'm handling the PHP part: ...

Override the CSS property in question

I have tackled numerous lines of pure CSS code, and I always knew where each property was coming from. However, the inline CSS works fine, but not the class/id. The doctype is correctly typed. Despite spending a significant amount of time researching, noth ...

Is there a way to delete both the item and its corresponding key from localStorage?

I have developed a basic application that utilizes localStorage for saving and deleting data. However, I encountered an issue where deleting an item only removes the value but not the key. As a result, when loading all items, the deleted ones appear as nul ...

Modifying the color of an empty string is not feasible in Javascript

Is it possible to change the color of FirstName only when there is text input? Currently, it turns green when there's text, but I want it to turn red when it's empty. How can this be achieved? $(document).on("click", '.btn-info.mailCo ...