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

Tips for enabling browser back and forward functionality in a one-page website design

Building on the previous discussion about optimizing a horizontal sliding layout (Most efficient way to do a horizontal sliding layout), I'm curious if it's feasible to enable the back and forward buttons in the browser when implementing a single ...

Could anyone provide some insight into the reason behind this occurrence?

I just came across the most peculiar situation I've ever experienced. Check out this unique test page: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <script language=javascript> fun ...

What is the best way to display the name of the user who has logged in using Facebook login?

After successfully implementing Facebook login using Passport.js, I encountered a problem with displaying the user's name in my React component. Despite correctly storing the id and name in the database on the backend, I struggled to retrieve and disp ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...

Converting a CSS Submenu from Horizontal to Vertical Orientation

Below is the current code snippet for my menu navigation bar: To access my live blog, please click on this link: www.4time2fun.com <div id="topmenu"> <div id="navigation"> <ul class="categories"> <li class="articles"> <a href ...

Preserve content from a hyperlink using JavaScript

How can I store a value to the cache using JavaScript when clicking on an anchor link? The code below sets up the dynamic content: <a align="left" href="projectoverview.html">Test Manager</a> I want to save the text "Test Manager" to the cach ...

What is the best way to initiate a re-render after updating state within useEffect()?

I'm currently strategizing the structure of my code using React hooks in the following manner: Implementing a state variable to indicate whether my app is loading results or not The loading state turns to true when useEffect() executes to retrieve da ...

creating a virtualized list using a separate file within a React application

I developed a task manager app in app.js along with a virtualized list in VirtualizedList.js, but for some reason the virtualized list code is not appearing even though I imported it correctly into app.js. Below is the code from VirtualizedList.js import ...

Utilize Node.js driver to export a Mongo collection into a JSON file

How can I export a MongoDB collection to a JSON format using the Node.js driver and fs.writeFile? ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...

Prevent users from inputting multiple minus signs by setting the input type to number and disabling the

Is there a way to prevent the input type number from accepting "--" as input? I am looking for a solution to disable this behavior. Additionally, the input field seems to allow for various incorrect formats like: -12-12 -- -121- 23-323- ...

Creating a personalized cover for devextreme column in datagrid: A Step-by-Step Guide

I have encountered an issue with wrapping a Column inside my DataGrid. My goal is to create a customized component that generates a Column with the correct formatting. For instance, I want to develop a ColumnDate component that includes specific date forma ...

Guide for displaying retrieved information on a Bootstrap Modal window following data submission in Yii2

I'm encountering an issue with a Modal popup that contains two fields. The first field is used to submit information and perform an internal database query, while the second field should display the returned data. Oddly enough, when testing the functi ...

Enhance your web form with the Bootstrap 4 tags input feature that allows users to add tags exclusively

I'm currently utilizing Bootstrap 4 along with Bootstrap Tags Input to create a multiple category selection feature. My goal is to enable users to choose multiple items exclusively from the predefined categories listed in the predefined_list. At pres ...

I am currently working on coding a function that will search an array to determine if a specific item is present. If the item is found, a variable will be set to true;

So, I have this array of prices for various items like bread, apple, noodles, beef, milk, and coke. const prices = [ ["bread", 20], ["apple", 50], ["noodles", 100], ["beef", 40], ["milk", 32], ["coke", 25], ]; And here's the JavaScript co ...

Is there a way to trigger a JavaScript function once AJAX finishes loading content?

I've been utilizing some code for implementing infinite scrolling on a Tumblr blog through AJAX, and it's been performing well except for the loading of specific Flash content. The script for the infinite scroll can be found here. To address the ...

Toggling designs with a simple click

I'm currently working on a ReactJS project and I'm trying to figure out how to change the color of a button when it's clicked. I've heard about the Ripple API, but I find it quite complex to use. Can anyone offer some advice on how I ca ...

Get the file using jQuery ajax post request

Currently, I am attempting to export the data from my web page and download it as an Excel file. However, despite receiving a successful response, the download does not initiate. $.ajax({ type: "POST", url: _url, contentType: 'multi ...

Convert Excel Spreadsheet data into an interactive HTML chart in real time

Looking for a solution to update an Excel spreadsheet monthly and display it on a Blackberry browser? I've already built a website with all the spreadsheet information using HTML lists and CSS for charts. I need help loading a new spreadsheet into th ...

Obtaining the value of an input field in HTML

I am currently working on a text input field that triggers a JavaScript function when a numeric value is entered. <input type="text" value="key" ng-keypress="submit(key)" ng-model="pager.page"/> Controller $scope.submit = function (val) { ...