How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page.

I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label and the bottom border of the input field. My goal is to only modify the font size once the Input field contains text.

Could you provide guidance on how I can achieve this?

Below is the code snippet that I have added to codesandbox

import React from "react";
import * as S from "./styles";

export default function App() {
  return (
    <div className="App">
      <S.Input label="Name" variant="standard" />
    </div>
  );
}
import styled from "styled-components";

import { TextField } from "@mui/material";

export const Input = styled(TextField)`
  && {
    .MuiInputBase-root {
      font-size: 30px;
    }
  }
`;

Thank you for any assistance provided.

https://i.stack.imgur.com/onl1s.png

https://i.stack.imgur.com/bk2kz.png

https://i.stack.imgur.com/yUgPM.png

https://i.stack.imgur.com/MlMcT.png

Answer №1

Here are a couple of methods, although I must admit that I have never really worked with mui components before.

Both solutions involve using magic numbers, which may not be the best practice to follow.

The initial solution entails adjusting the y position of the label both at the start and when the text area is focused. Check out the sandbox link for more details.

export const Input = styled(TextField)`
  && {
    .MuiInputBase-root {
      font-size: 30px;
    }
    .MuiInputLabel-root {
      transform: translateY(40px);
    }
    .Mui-focused {
      transform: translateY(0px);
    }
  }
`;

The second method is quite similar, but this time it involves using line-height instead. Once again, utilizing classes for the focused and initial label states.

export const Input = styled(TextField)`
  && {
    .MuiInputBase-root {
      font-size: 30px;
    }
    .MuiInputLabel-root {
      line-height: 60px;
    }
    .Mui-focused {
      line-height: 22px;
    }
  }
`;

Answer №2

An effective method using only CSS is by utilizing the :placeholder-shown pseudo selector.

The placeholder text will be visible only when the input field is empty or not filled in.

label{
  user-select:none;
  display:block;
}

input{
  border:none;
  border-bottom:1px solid #000;
  transition:0.3s;
}

input:invalid,
input:placeholder-shown{
  transform:translateY(-75%);
  background:transparent;
}

input::placeholder {
  color: transparent;
}


input:focus{
  transform:translateY(0%);
  font-size:2em;
  outline:none;
  border-bottom:1px solid red;
}
<p>
  <label>Name</label>
  <input class="MuiInput-input" value="" placeholder="placeholder">
</p>
<p>
  <label>Last name*</label>
  <input type="text" class="MuiInput-input" value="" required>
</p>

The support for this pseudo-selector is quite robust and widely available.

If necessary, you can also leverage the use of input:invalid selectors for enforcing input requirements in a similar manner.

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

Using a Javascript while loop to iterate through an array and display the elements in the .innerHTML property

As a newcomer to Javascript, I am in the process of teaching myself. My current task is to develop a function that will display each element of the array AmericanCars with a space between them. I have successfully been able to show an individual element u ...

The issue of gallery image loading with the galleryView jQuery plugin is causing problems

Hi fellow developers, I could really use some assistance. I've been working on implementing the jquery galleryview plugin for my image gallery (check out my gallery here). Unfortunately, I'm running into an issue where the gallery is not loading ...

Having trouble with parameter-based navigation in React?

Currently, I am attempting to implement a route in my app.js file with the path /product and a parameter of id specified. In app.js: <Route path='/product' element={<Product />} /> Within Product.js: export const Product = ({ ID } ...

Injecting universal data into ValidationErrors in Angular

Trying to bind a value into ValidationErrors. Having this method: isUniqueEmail(control: FormControl): ValidationErrors { if (control.value != null) { console.log(control.value) if(control.value == this.foundEmail){ console ...

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

The react-speech-recognition encountered an issue and failed during the hydration process

Recently, I decided to experiment with speech recognition in NextJS 13. Following the installation of react-speech-recognition, I simply copied and pasted the provided example code. Unfortunately, I encountered an issue stating: Error: Hydration failed bec ...

The issue with Three.Js Raycasting arises when attempting to change camera transformations within an Object3D parent element

In my latest project, I decided to create a "camera controller" that handles the movement and rotation of the camera by utilizing an Object3D as its parent. The Y-axis rotations are applied to the Object3D, while the X-axis rotation is directly applied to ...

Is there a more effective approach to managing an array of objects retrieved from an API call?

I'm attempting to extract an array of names from a JSON response that contains an array of objects, but I'm running into issues. When I try to print the array, it shows up empty. Is this the correct way to go about it? There don't seem to be ...

Is it possible to pass an external function to the RxJs subscribe function?

Upon examining the RxJS subscribe method, I noticed that: subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription; So, I decided to create an example initialization function like this: private ...

Modify the scoped variable using Angular's $resource module

I am facing an issue with my Angular application where I cannot get the results of a second $resource call to update a scoped variable. Initially, I am able to generate the initial view from an Angular $resource call to an external API and display the data ...

Place form at the center of the Bootstrap Modal

My question is, how can I center the entire form, including the input fields and labels, within the modal? Here is also a helpful Fiddle: http://example.com, although the snippet provided should work as well. <script src="https://example.com/bootstr ...

Ways to automatically include a local variable in all functions

In each of my functions, I start with this specific line: var local = {} By doing so, it allows me to organize my variables using the following structure: local.x = 1 local.y = 2 Is there a way to modify all function prototypes to automatically include ...

What could be causing the background image on my element to not update?

I'm attempting to utilize a single background image that is 3 pixels wide and 89 pixels tall. Each vertical stripe of 1 pixel will serve as the background for a different div. I had presumed that adjusting the background-position by -1px 0 and specif ...

Ways to deactivate a button using CSS

I need to use Javascript to disable a link based on its id. By default, the link is invisible. I will only enable the link when the specific id value comes from the backend. HTML <li id="viewroleId" style="display: none;"> <a href="viewrole" ...

How can AJAX be used to execute a PHP script that deletes a record from a database table?

Yesterday, I asked for help on how to save user-generated blog posts and I successfully tackled the database aspect of it. Now, my next goal is to be able to delete a blog post upon clicking a button with an onclick event. After researching extensively onl ...

Ways to align a bootstrap 4 row both vertically and horizontally in the center amidst other rows

Assume there is a main menu followed by three rows. The first row should be at the top and the third at the bottom, while the second row needs to be centered both vertically and horizontally. As you scroll down, the main menu should be able to hide while ...

Is there a way to assign "label 3" with the identical percentage as "label 1" on this particular form?

I'm currently using Bootstrap 4 for my project. I want to adjust "label 3" to have the same width as "label 1," while keeping the input width and the rest of the page intact (as shown in the code). Is this possible to achieve? Thank you. https://i ...

Ways to unlock all the information windows in Google Maps

Is it possible to automatically display all info windows on the map when it is first opened, eliminating the need for users to click on markers? In other words, I would like all info windows for all markers to be shown by default when the map is opened. ...

The significance of having spaces in the PATH for npm

Attempting to set up gulp, but encountering the following error: module.js:471^throw err : cannot find module 'C:\c\Users\Joe's Steezy Laptop\AppData\Roaming\npm\node_modules\gulp-cli\bin\gul ...