CSS Media Features - Width



CSS media feature width is used to determine the width (horizontal dimension) of the viewport (browser's viewing area).

The width media feature can also be used with the min-width and max-width properties to set the minimum and maximum width of the viewport.

Possible Values

  • <length> − The width of the viewport is represented by a specific length value, such as pixels (px) etc.

Syntax

 @media (width: <length>){ //CSS styles } 

CSS width - <length> Value

The following example demonstrates that the width media feature to change the background color to pink when the screen width is 200px −

 <html> <head> <style> iframe { display: block; } </style> </head> <body> <label id="labelWidth" for="height">Width: 100</label> <input id="width" name="width" type="range" min="100" max="300" step="5" value="100" /> <iframe id="block" srcdoc="<style> @media (width: 200px) { div { background: pink; } } </style><div>To see the effect resize your viewport's width is 200px.</div>"> </iframe> <script> const updateSize = (size, label) => { block.style[size] = `${eval(size).value}px`; label.textContent = `${size}: ${eval(size).value}`; }; width.oninput = () => updateSize("width", labelWidth); </script> </body> </html> 

CSS width - min-width Variant

The following example demonstrates that the min-width media feature to change the background color to red when the screen width is greater than or equal to 200px

 <html> <head> <style> iframe { display: block; } </style> </head> <body> <label id="labelWidth" for="height">Width: 200</label> <input id="width" name="width" type="range" min="100" max="300" step="5" value="200" /> <iframe id="block" srcdoc="<style> @media (min-width: 200px) { div { background: red; } } </style><div>To see the effect resize your viewport's width.</div>"> </iframe> <script> const updateSize = (size, label) => { block.style[size] = `${eval(size).value}px`; label.textContent = `${size}: ${eval(size).value}`; }; width.oninput = () => updateSize("width", labelWidth); </script> </body> </html> 

CSS width - max-width Variant

The following example demonstrates that the max-width media feature to change the background color to pink when the screen width is less than or equal to 250px

 <html> <head> <style> iframe { display: block; } </style> </head> <body> <label id="labelWidth" for="height">Width: 100</label> <input id="width" name="width" type="range" min="100" max="300" step="5" value="100" /> <iframe id="block" srcdoc="<style> @media (max-width: 250px) { div { background: pink; } } </style><div>To see the effect resize your viewport's width.</div>"> </iframe> <script> const updateSize = (size, label) => { block.style[size] = `${eval(size).value}px`; label.textContent = `${size}: ${eval(size).value}`; }; width.oninput = () => updateSize("width", labelWidth); </script> </body> </html> 
Advertisements