Setting max-width on an input element

12,723

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

Share:
12,723
bodacydo
Author by

bodacydo

My name is Boda Cydo. I am from Africa but now live in Washington DC.

Updated on June 24, 2022

Comments

  • bodacydo
    bodacydo almost 2 years

    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?

  • Lee
    Lee over 4 years
    Are you sure this isn't the other way around? In your example changing the % width does nothing, but changing the px does...
  • T04435
    T04435 about 4 years
    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%;