6

Today I tried setting max-width: 200px on an <input type="text"> but apparently it gets ignored by browsers.

If I set width: 200px then it properly gets applied (but doesn't get resized if input field gets resized smaller than 200px.

How do I apply max-width CSS property to input fields?

1

2 Answers 2

3

If you set max-width:200px; then you have to set the width in a relative unit like %. Because if you set width:200px the site of the input is not going to change;

this is an example

  <!DOCTYPE html>
    <html>
    <head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title></title>
	<link rel="stylesheet" href="">
	<style type="text/css" media="screen">
		div{
			background-color: tomato;
			width: 100%;
			max-width: 1024px;
			margin: auto;
		}
		input{
			margin: auto;
			background-color: red;
			display: block;
			margin-bottom: 2rem;
		}
		input#no-fluid{
			border:2px black dotted;
			width: 200px;
			max-width: 300px;
		}
		input#fluid{
			border:2px black solid;
			width: 50%;
			max-width: 300px;
		}
	</style>
    </head>
    <body>
	<div>
		<input id="no-fluid" type="text">
		<input id="fluid" type="text">
	</div>

    </body>
    </html>

The fluid input will change its width as you resize the screen, but only up to 300px(max-width). The non fluid on will keep its width, even if you resize the screen

HOPE this helps T04435

Sign up to request clarification or add additional context in comments.

2 Comments

Are you sure this isn't the other way around? In your example changing the % width does nothing, but changing the px does...
The % will only change the width when the viewport is below 600px. given that the max-width is set to 300px and the width to 50%;
0

Another thing you can do is set the max-width to 200px and then you can set the width to anything using width: 200px. even if you exceed the max-width, its maximum width would always be 200px and if you resize it to smaller than 200px it will resize smaller to 200px. And you can play around it with this jsfiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.