├── .gitignore ├── LICENSE-GPL.txt ├── LICENSE-MIT.txt ├── README.md ├── demo └── index.html ├── dist ├── viewport-scale.js ├── viewport-scale.min.js └── viewportSize-min.js └── package.json /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/neilg63/viewportScale/2e37fe129f6d9803b763af57f4d666b25f39782b/.gitignore -------------------------------------------------------------------------------- /LICENSE-GPL.txt: -------------------------------------------------------------------------------- 1 | Copyright Neil Gardner 2 | 3 | GNU GENERAL PUBLIC LICENSE 4 | Version 2, June 1991 5 | 6 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 7 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 8 | Everyone is permitted to copy and distribute verbatim copies 9 | of this license document, but changing it is not allowed. 10 | 11 | Preamble 12 | 13 | The licenses for most software are designed to take away your 14 | freedom to share and change it. By contrast, the GNU General Public 15 | License is intended to guarantee your freedom to share and change free 16 | software--to make sure the software is free for all its users. This 17 | General Public License applies to most of the Free Software 18 | Foundation's software and to any other program whose authors commit to 19 | using it. (Some other Free Software Foundation software is covered by 20 | the GNU Lesser General Public License instead.) You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | this service if you wish), that you receive source code or can get it 27 | if you want it, that you can change the software or use pieces of it 28 | in new free programs; and that you know you can do these things. 29 | 30 | To protect your rights, we need to make restrictions that forbid 31 | anyone to deny you these rights or to ask you to surrender the rights. 32 | These restrictions translate to certain responsibilities for you if you 33 | distribute copies of the software, or if you modify it. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must give the recipients all the rights that 37 | you have. You must make sure that they, too, receive or can get the 38 | source code. And you must show them these terms so they know their 39 | rights. 40 | 41 | We protect your rights with two steps: (1) copyright the software, and 42 | (2) offer you this license which gives you legal permission to copy, 43 | distribute and/or modify the software. 44 | 45 | Also, for each author's protection and ours, we want to make certain 46 | that everyone understands that there is no warranty for this free 47 | software. If the software is modified by someone else and passed on, we 48 | want its recipients to know that what they have is not the original, so 49 | that any problems introduced by others will not reflect on the original 50 | authors' reputations. 51 | 52 | Finally, any free program is threatened constantly by software 53 | patents. We wish to avoid the danger that redistributors of a free 54 | program will individually obtain patent licenses, in effect making the 55 | program proprietary. To prevent this, we have made it clear that any 56 | patent must be licensed for everyone's free use or not licensed at all. 57 | 58 | The precise terms and conditions for copying, distribution and 59 | modification follow. 60 | 61 | GNU GENERAL PUBLIC LICENSE 62 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 63 | 64 | 0. This License applies to any program or other work which contains 65 | a notice placed by the copyright holder saying it may be distributed 66 | under the terms of this General Public License. The "Program", below, 67 | refers to any such program or work, and a "work based on the Program" 68 | means either the Program or any derivative work under copyright law: 69 | that is to say, a work containing the Program or a portion of it, 70 | either verbatim or with modifications and/or translated into another 71 | language. (Hereinafter, translation is included without limitation in 72 | the term "modification".) Each licensee is addressed as "you". 73 | 74 | Activities other than copying, distribution and modification are not 75 | covered by this License; they are outside its scope. The act of 76 | running the Program is not restricted, and the output from the Program 77 | is covered only if its contents constitute a work based on the 78 | Program (independent of having been made by running the Program). 79 | Whether that is true depends on what the Program does. 80 | 81 | 1. You may copy and distribute verbatim copies of the Program's 82 | source code as you receive it, in any medium, provided that you 83 | conspicuously and appropriately publish on each copy an appropriate 84 | copyright notice and disclaimer of warranty; keep intact all the 85 | notices that refer to this License and to the absence of any warranty; 86 | and give any other recipients of the Program a copy of this License 87 | along with the Program. 88 | 89 | You may charge a fee for the physical act of transferring a copy, and 90 | you may at your option offer warranty protection in exchange for a fee. 91 | 92 | 2. You may modify your copy or copies of the Program or any portion 93 | of it, thus forming a work based on the Program, and copy and 94 | distribute such modifications or work under the terms of Section 1 95 | above, provided that you also meet all of these conditions: 96 | 97 | a) You must cause the modified files to carry prominent notices 98 | stating that you changed the files and the date of any change. 99 | 100 | b) You must cause any work that you distribute or publish, that in 101 | whole or in part contains or is derived from the Program or any 102 | part thereof, to be licensed as a whole at no charge to all third 103 | parties under the terms of this License. 104 | 105 | c) If the modified program normally reads commands interactively 106 | when run, you must cause it, when started running for such 107 | interactive use in the most ordinary way, to print or display an 108 | announcement including an appropriate copyright notice and a 109 | notice that there is no warranty (or else, saying that you provide 110 | a warranty) and that users may redistribute the program under 111 | these conditions, and telling the user how to view a copy of this 112 | License. (Exception: if the Program itself is interactive but 113 | does not normally print such an announcement, your work based on 114 | the Program is not required to print an announcement.) 115 | 116 | These requirements apply to the modified work as a whole. If 117 | identifiable sections of that work are not derived from the Program, 118 | and can be reasonably considered independent and separate works in 119 | themselves, then this License, and its terms, do not apply to those 120 | sections when you distribute them as separate works. But when you 121 | distribute the same sections as part of a whole which is a work based 122 | on the Program, the distribution of the whole must be on the terms of 123 | this License, whose permissions for other licensees extend to the 124 | entire whole, and thus to each and every part regardless of who wrote it. 125 | 126 | Thus, it is not the intent of this section to claim rights or contest 127 | your rights to work written entirely by you; rather, the intent is to 128 | exercise the right to control the distribution of derivative or 129 | collective works based on the Program. 130 | 131 | In addition, mere aggregation of another work not based on the Program 132 | with the Program (or with a work based on the Program) on a volume of 133 | a storage or distribution medium does not bring the other work under 134 | the scope of this License. 135 | 136 | 3. You may copy and distribute the Program (or a work based on it, 137 | under Section 2) in object code or executable form under the terms of 138 | Sections 1 and 2 above provided that you also do one of the following: 139 | 140 | a) Accompany it with the complete corresponding machine-readable 141 | source code, which must be distributed under the terms of Sections 142 | 1 and 2 above on a medium customarily used for software interchange; or, 143 | 144 | b) Accompany it with a written offer, valid for at least three 145 | years, to give any third party, for a charge no more than your 146 | cost of physically performing source distribution, a complete 147 | machine-readable copy of the corresponding source code, to be 148 | distributed under the terms of Sections 1 and 2 above on a medium 149 | customarily used for software interchange; or, 150 | 151 | c) Accompany it with the information you received as to the offer 152 | to distribute corresponding source code. (This alternative is 153 | allowed only for noncommercial distribution and only if you 154 | received the program in object code or executable form with such 155 | an offer, in accord with Subsection b above.) 156 | 157 | The source code for a work means the preferred form of the work for 158 | making modifications to it. For an executable work, complete source 159 | code means all the source code for all modules it contains, plus any 160 | associated interface definition files, plus the scripts used to 161 | control compilation and installation of the executable. However, as a 162 | special exception, the source code distributed need not include 163 | anything that is normally distributed (in either source or binary 164 | form) with the major components (compiler, kernel, and so on) of the 165 | operating system on which the executable runs, unless that component 166 | itself accompanies the executable. 167 | 168 | If distribution of executable or object code is made by offering 169 | access to copy from a designated place, then offering equivalent 170 | access to copy the source code from the same place counts as 171 | distribution of the source code, even though third parties are not 172 | compelled to copy the source along with the object code. 173 | 174 | 4. You may not copy, modify, sublicense, or distribute the Program 175 | except as expressly provided under this License. Any attempt 176 | otherwise to copy, modify, sublicense or distribute the Program is 177 | void, and will automatically terminate your rights under this License. 178 | However, parties who have received copies, or rights, from you under 179 | this License will not have their licenses terminated so long as such 180 | parties remain in full compliance. 181 | 182 | 5. You are not required to accept this License, since you have not 183 | signed it. However, nothing else grants you permission to modify or 184 | distribute the Program or its derivative works. These actions are 185 | prohibited by law if you do not accept this License. Therefore, by 186 | modifying or distributing the Program (or any work based on the 187 | Program), you indicate your acceptance of this License to do so, and 188 | all its terms and conditions for copying, distributing or modifying 189 | the Program or works based on it. 190 | 191 | 6. Each time you redistribute the Program (or any work based on the 192 | Program), the recipient automatically receives a license from the 193 | original licensor to copy, distribute or modify the Program subject to 194 | these terms and conditions. You may not impose any further 195 | restrictions on the recipients' exercise of the rights granted herein. 196 | You are not responsible for enforcing compliance by third parties to 197 | this License. 198 | 199 | 7. If, as a consequence of a court judgment or allegation of patent 200 | infringement or for any other reason (not limited to patent issues), 201 | conditions are imposed on you (whether by court order, agreement or 202 | otherwise) that contradict the conditions of this License, they do not 203 | excuse you from the conditions of this License. If you cannot 204 | distribute so as to satisfy simultaneously your obligations under this 205 | License and any other pertinent obligations, then as a consequence you 206 | may not distribute the Program at all. For example, if a patent 207 | license would not permit royalty-free redistribution of the Program by 208 | all those who receive copies directly or indirectly through you, then 209 | the only way you could satisfy both it and this License would be to 210 | refrain entirely from distribution of the Program. 211 | 212 | If any portion of this section is held invalid or unenforceable under 213 | any particular circumstance, the balance of the section is intended to 214 | apply and the section as a whole is intended to apply in other 215 | circumstances. 216 | 217 | It is not the purpose of this section to induce you to infringe any 218 | patents or other property right claims or to contest validity of any 219 | such claims; this section has the sole purpose of protecting the 220 | integrity of the free software distribution system, which is 221 | implemented by public license practices. Many people have made 222 | generous contributions to the wide range of software distributed 223 | through that system in reliance on consistent application of that 224 | system; it is up to the author/donor to decide if he or she is willing 225 | to distribute software through any other system and a licensee cannot 226 | impose that choice. 227 | 228 | This section is intended to make thoroughly clear what is believed to 229 | be a consequence of the rest of this License. 230 | 231 | 8. If the distribution and/or use of the Program is restricted in 232 | certain countries either by patents or by copyrighted interfaces, the 233 | original copyright holder who places the Program under this License 234 | may add an explicit geographical distribution limitation excluding 235 | those countries, so that distribution is permitted only in or among 236 | countries not thus excluded. In such case, this License incorporates 237 | the limitation as if written in the body of this License. 238 | 239 | 9. The Free Software Foundation may publish revised and/or new versions 240 | of the General Public License from time to time. Such new versions will 241 | be similar in spirit to the present version, but may differ in detail to 242 | address new problems or concerns. 243 | 244 | Each version is given a distinguishing version number. If the Program 245 | specifies a version number of this License which applies to it and "any 246 | later version", you have the option of following the terms and conditions 247 | either of that version or of any later version published by the Free 248 | Software Foundation. If the Program does not specify a version number of 249 | this License, you may choose any version ever published by the Free Software 250 | Foundation. 251 | 252 | 10. If you wish to incorporate parts of the Program into other free 253 | programs whose distribution conditions are different, write to the author 254 | to ask for permission. For software which is copyrighted by the Free 255 | Software Foundation, write to the Free Software Foundation; we sometimes 256 | make exceptions for this. Our decision will be guided by the two goals 257 | of preserving the free status of all derivatives of our free software and 258 | of promoting the sharing and reuse of software generally. 259 | 260 | NO WARRANTY 261 | 262 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 263 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 264 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 265 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 266 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 267 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 268 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 269 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 270 | REPAIR OR CORRECTION. 271 | 272 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 273 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 274 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 275 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 276 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 277 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 278 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 279 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 280 | POSSIBILITY OF SUCH DAMAGES. -------------------------------------------------------------------------------- /LICENSE-MIT.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Neil Gardner 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | jQuery viewportScale 2 | ============= 3 | 4 | This simple jQuery plugin (compatible with jQuery 1.7+ and 2.*.x) lets you apply responsive viewport size units (vw, vh, vmax and vmin) with browsers with incomplete CSS3 support. See W3C: CSS Values and Units Module Level 3 for more details on these properties. 5 | 6 | In fluid design, the width of HTML elements can always be calculated in percent as long as the document body has a known percentage value, although percentage width and height are always relative to their parent element's width and height. However, until recently without Javascript it was impossible to scale an element based on viewport height alone. This technique has become very common in mobile designs, e.g. where a page section is designed to occupy the whole screen height and width, but more content is available by scrolling up or down. Viewport height (vh) units are the answer. 7 | 8 | When applied to font-sizes, viewport width (vw) is a lightweight alternative to fit-text scripts to ensure text always occupies approximately the same proportion of the screen width and thus take up the same number of lines. 9 | 10 |

Browser Support Detection

11 | 12 | The plugin can optionally run a basic viewport unit support test. This will only run once as it adds two class names to the HTML body tag. 13 | 14 | Some common browsers such as IOS Safari before version 7 and Internet Explorer before version 10 provide partial support. The test ensures a hidden element sized in vh matches its expected size based on viewport height. See Can I Use Viewport units for more detailed analysis. 15 | 16 | For a practical example please view this simple demo . 17 | 18 | As of November 2014, the latest official version of all major browsers support vw, vh, vmax and vmin. However, if you need to support IE8, IE9 (partial support), Safari < 7 (no support), iOS Safari < 7.1, you may target this plugin only at users of these browsers and let modern browsers use CSS only. 19 | 20 |

A simple demo shows you the desired effects

21 | 22 |

Correct Viewport Width

23 | 24 | Before the introduction of CSS viewport units, browsers did not consistently distinguish between window width with or without scrollbars. Most mobile browsers and some desktop browsers hide scrollbars when not scrolling and thus report Javascript's window.outerWidth to be exactly 100vw. However, most desktop browsers subtract the scrollbar width from this value. As a result, 100% of window width is always not the same as 100vw. If you wish to ensure exact compatibility with W3C definition of viewport width, please include Tyson Matanich's 25 | viewportSize. This is not necessary if you require only viewport heights (vh) or do not mind discrepencies in viewport width when scrollbars are always present. 26 | 27 |

Requirements

28 | 29 |
    30 |
  1. jQuery 1.7+, jQuery 2.* and hopefully jQuery 3.*
  2. 31 |
  3. Optionally load the viewportSize script first. This adds a new window.viewportSize object
  4. 32 |
  5. Load the viewportScale plugin
  6. 33 |
  7. Use it in your custom javascript within a jQuery context.
  8. 34 |
35 | 36 |

How it works

37 | 38 | On initial page load the script gauges the correct window height and width (optionally with the aid of viewportSize to gauge correct viewport width without scrollbars). It then translates these into pixel values for the following properties: 39 | 40 |
    41 |
  1. width
  2. 42 |
  3. height
  4. 43 |
  5. top
  6. 44 |
  7. bottom
  8. 45 |
  9. left
  10. 46 |
  11. right
  12. 47 |
  13. min-width
  14. 48 |
  15. min-height
  16. 49 |
  17. max-width
  18. 50 |
  19. max-height
  20. 51 |
  21. font-size
  22. 52 |
53 | 54 | The plugin does not support other common properties, as these can be derived from the above using relative units, e.g. padding and margin in em's are relative the font-size and layout properties in percent are relative to their parent elements. 55 | 56 | The plugin will recalculate these values when the browser window is resized or the screen orientation is flipped. 57 | 58 |

Sample usage:

59 | 60 | This plugin is best suited for situations where viewport units are only used sparingly for a few strategic layout elements or text that must fit within those elements (a great alternative to Fit-Text). 61 | 62 | If you need to target a large set of HTML objects matching one or more CSS paths, the plugin will generate inline markup for each element and will recalculate these values when browser windows are resized and thus potentially consume more resources, especially in older browsers. 63 | 64 |

Options:

65 |
66 |
resize:
Default = true, to disable automatic resizing of inline styles applied by this plugin on window resize enter false.
67 |
detect:
Default = 'full', unless only simplified string syntax is used in the first parameter, in which case only a basic test is run. Use 'skip' to suppress browser detection altogether. To enforce full suppprt detection even with simplified vw/vh syntax, specify 'strict' for this option.
68 |
sizeMode:
Default = 'auto', define whether the initial viewport size detection script should be based on application window height, as is preferable in a desktop environment or on screen height, as is preferable for mobile device in which the browser is usually fullscreen except when nagivation controls are displayed. Auto mode assumes if the initial window height is below a certain value (480 by default) it should assume screen height is the better unit, although this may include some smaller desktop/laptop screens. In 'mobile' mode screen height is enforced and in desktop mode, only true window height is considered. You can use a third party deivce detection script to apply the best setting.
69 |
maxMobileHeight:
Default = 480, define the maximum initial window height at which a device is considered mobile. We recommend using a device detection script.
70 |
71 | 72 |

iOS Screen Height Issue

73 |

iOS subtracts the navigation bar from the window height, even if its hidden on page load. As a result only screen.height is a reliable measure for such devices.

74 |

Basic Usage

75 |

For basic usage when applying viewport height or width to CSS height or width properties, you need only add a comma separated string:

76 | 77 |
 78 | 	/* Exactly 80% of viewport height irrespective of page length
 79 | 	* most common use case, translates to 
 80 | 	* #my-element { height: 80vh; }
 81 | 	*/
 82 | 	$('#my-element').viewportScale('80vh');
 83 | 
84 | 85 |
 86 | 	/* Exactly 50% of viewport height and 25% of viewport width 
 87 | 	* Translates to:
 88 | 	* #my-element { height: 50vh; width: 25vw; }
 89 | 	*/
 90 | 	$('#my-element').viewportScale('50vh,25vw');
 91 | 
92 | 93 | For other supported combinations, use object notation: 94 | 95 |
 96 | 	/* Height, width and font-size scaled to match viewport width only 
 97 | 	* Translates to:
 98 | 	* #my-element { max-height: 30vw; width: 20vw; font-size: 2vw; }
 99 | 	*/
100 | 	$('#my-element').viewportScale({
101 | 		'max-height': '30vw',
102 | 		 width: '20vw',
103 | 		'font-size': '2vw'
104 | 	});
105 | 
106 | 107 |

HTML Snippet:

108 |
109 | <section class="half-width-height">
110 | 	<p> Scalable text 2% of viewport height or width, whichever is the largest</p>
111 | </section>
112 | 
113 | <section class="third-width-fixed-aspect">
114 | 	<p> Fixed aspect ratio relative to screen width only. </p>
115 | </section>
116 | 
117 | 
118 | 119 |

Stylesheet:

120 |
121 | section.half-width-height {
122 |   position: relative;
123 |   width: 50vw; /* viewport width, not supported in IE8*/
124 |   height: 50vh; /* viewport height, not supported in IE8*/
125 | 	border: dashed 3px #999999;
126 | 	background-color: #ffff66;
127 | 	margin: 5%;
128 | }
129 | 
130 | section.half-width-height p {
131 |   font-size: 2vmax;
132 | }
133 | 
134 | section.third-width-fixed-aspect {
135 |   position: relative;
136 |   width: 33.333vw; /* viewport width, not supported in IE8*/
137 |   height: 33.333vh; /* viewport height, not supported in IE8*/
138 | 	border: dashed 3px #999999;
139 | 	background-color: #9999ff;
140 | 	margin: 5%;
141 | }
142 | 
143 | 
144 | 145 |

Javascript in jQuery context:

146 |
147 | 	
148 | /* Optionally include and instantiate viewportSize to add window.viewportSize.getWidth() method */
149 | 
150 | viewportSize.getWidth();
151 | 	
152 | /* simple set up for only height and width using vh and vw units respectively */
153 | $('section.half-width-height').viewportScale('50vh,50vw');
154 | 
155 | /* For other units and combinations use object notation */
156 | $('section.half-width-height p').viewportScale({
157 | 	'font-size': '2vmax'
158 | });
159 | 
160 | /* For other units and combinations use object notation */
161 | $('section.third-width-fixed-aspect').viewportScale({
162 | 	'width': '33.333vw',
163 | 	'height': '33.333vw',
164 | });
165 | 
166 | 
167 | 168 |

Resize Events

169 | 170 | The plugin responds to window resizing and changes in screen orientation. If you use this plugin within a resize event handler, you may want to disable this feature, by just adding false as the second parameter. 171 | 172 |
173 | 			/* only set on initial page load  or in response to other triggers */
174 | 			$('#my-container').viewPortScale({'font-size': '3vw'}, false);
175 | 	
176 | 
177 | 178 |

Configure Browser Support Detection

179 |

The detection function temporarily creates an empty div, to which it applies a height of 100vh, a font-size of 2vh and in full or strict mode a width of 50vmax. After appending it to the body it checks its height matches the correct viewport height (outerHeight) and its font-size translated into pixels is approximately 1/50 of that. In strict mode it will detect vmax, which is not supported in Internet Explorer 9-11. In basic mode, where only vw and vh units are required, IE9 to 11 should pass the test.

180 |

By contrast iOS Safari fails to support vh correctly and thus before version 8 failed both tests.

181 | 182 |

To suppress this test and always apply inline translated pixel-based styles, you may specify detect mode as the second options parameter of viewportScale(). When using simplified string syntax in the first parameter, the plugin will only run a basic test e.g.

183 | 184 |
185 | 			/* Apply basic test only, as vmax and vmin are not required */
186 | 			$('#my-container').viewPortScale(
187 | 					{
188 | 						'font-size':
189 | 						'3vw'
190 | 					},
191 | 					{
192 | 						detect:'basic'
193 | 					}
194 | 				);
195 | 	
196 | 
197 | 198 |
199 | 			/* Always apply irrespective of browser support, skip browser detection */
200 | 			$('#my-container').viewPortScale(
201 | 				{
202 | 					'font-size': '3vw'
203 | 				},
204 | 				{
205 | 					detect:'skip'
206 | 			});
207 | 	
208 | 
209 | 210 | -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | jQuery viewport Scale Demo 7 | 8 | 13 | 14 | 15 | 16 | 17 | 183 | 184 | 185 | 186 | 187 | 188 |
189 |

viewportScale Plugin Example

190 |

Get it from GitHub !

191 |

192 |
193 |
194 | 195 |
196 |

Always proportional viewport width and height

197 |
    198 |
  • width: 25% viewport width
  • 199 |
  • height: 25% viewport height
  • 200 |
201 |
202 | 203 |
204 |

Fixed aspect ratio

205 |
    206 |
  • width: 25% view width
  • 207 |
  • height: 25% viewport width
  • 208 |
209 |

210 | 211 |

212 |
213 | 214 |
215 |

Text scaled to fit within fixed aspect-ratio element relative to maximum viewport dimension

216 |
    217 |
  • font-size: 1.5% of larger of viewport height or width (vmax)
  • 218 |
  • width: 20vmax
  • 219 |
  • height: 30vmax
  • 220 |
221 |
222 |
223 | 224 |
225 |
226 |

Fit-Text Example, translated size:

227 |

Base font-size in this region: 2vw, translated size:

228 |
229 |
230 | 231 |
232 |

jQuery viewportScale

233 | 234 |

This simple jQuery plugin lets you apply responsive viewport size units (vw, vh, vmax and vmin) with browsers with incomplete CSS3 support. See W3C: CSS Values and Units Module Level 3 for more details on these properties.

235 | 236 |

In fluid design, the width of HTML elements can always be calculated in percent as long as the document body has a known percentage value, although percentage width and height are always relative to their parent element's width and height. However, until recently without Javascript it was impossible to scale an element based on viewport height alone. This technique has become very common in mobile designs, e.g. where a page section is designed to occupy the whole screen height and width, but more content is available by scrolling up or down. Viewport height (vh) units are the answer.

237 | 238 |

When applied to font-sizes, viewport width (vw) is a lightweight alternative to fit-text scripts to ensure text always occupies approximately the same proportion of the screen width and thus take up the same number of lines.

239 | 240 |

Browser Support Detection

241 | 242 |

The plugin can optionally run a basic viewport unit support test. This will only run once as it adds two class names to the HTML body tag.

243 | 244 |

Some common browsers such as IOS Safari before version 7 and Internet Explorer before version 10 provide partial support. The test ensures a hidden element sized in vh matches its expected size based on viewport height. See Can I Use Viewport units for more detailed analysis.

245 | 246 |

As of November 2014, the latest official version of all major browsers support vw, vh, vmax and vmin. However, if you need to support IE8, IE9 (partial support), Safari < 7 (no support), iOS Safari < 7.1.

247 | 248 |

Correct Viewport Width

249 |

Before the introduction of CSS viewport units, browsers did not consistently distinguish between window width with or without scrollbars. Most mobile browsers and some desktop browsers hide scrollbars when not scrolling and thus report Javascript's window.outerWidth to be exactly 100vw. However, most desktop browsers substract the scrollbar width from this value. As a result, 100% of window width is always not the same as 100vw. If you wish to ensure exact compatibility with W3C definition of viewport width, please include Tyson Matanich's 250 | viewportSize. This is not necessary if you require only viewport heights (vh) or do not mind discrepencies in viewport width when scrollbars are always present.

251 | 252 |

Requirements

253 | 254 |
    255 |
  1. jQuery 1.7+, jQuery 2.* and hopefully jQuery 3.*
  2. 256 |
  3. Optionally load the viewportSize script first. This adds a new window.viewportSize object
  4. 257 |
  5. Load the viewportScale plugin
  6. 258 |
  7. Use it in your custom javascript within a jQuery context.
  8. 259 |
260 | 261 |

How it works

262 |

On initial page load the script gauges the correct window height and width (optionally with the aid of viewportSize to gauge correct viewport width without scrollbars). It then translates these into pixel values for the following properties:

263 | 264 |
    265 |
  1. width
  2. 266 |
  3. height
  4. 267 |
  5. top
  6. 268 |
  7. bottom
  8. 269 |
  9. left
  10. 270 |
  11. right
  12. 271 |
  13. min-width
  14. 272 |
  15. min-height
  16. 273 |
  17. max-width
  18. 274 |
  19. max-height
  20. 275 |
  21. font-size
  22. 276 |
277 | 278 |

The plugin does not support other common properties, as these can be derived from the above using relative units, e.g. padding and margin in em's are relative the font-size and layout properties in percent are relative to their parent elements.

279 | 280 |

The plugin will recalculate these values when the browser window is resized or the screen orientation is flipped.

281 | 282 |

Sample usage:

283 | 284 |

This plugin is best suited for situations where viewport units are only used sparingly for a few strategic layout elements or text that must fit within those elements (a great alternative to Fit-Text).

285 | 286 |

If you need to target a large set of HTML objects matching one or more CSS paths, the plugin will generate inline markup for each element and will recalculate these values when browser windows are resized and thus potentially consume more resources, especially in older browsers.

287 | 288 |

Options:

289 |
290 |
resize:
Default = true, to disable automatic resizing of inline styles applied by this plugin on window resize enter false.
291 |
detect:
Default = 'full', unless only simplified string syntax is used in the first parameter, in which case only a basic test is run. Use 'skip' to suppress browser detection altogether. To enforce full suppprt detection even with simplified vw/vh syntax, specify 'strict' for this option.
292 |
sizeMode:
Default = 'auto', define whether the initial viewport size detection script should be based on application window height, as is preferable in a desktop environment or on screen height, as is preferable for mobile device in which the browser is usually fullscreen except when nagivation controls are displayed. Auto mode assumes if the initial window height is below a certain value (480 by default) it should assume screen height is the better unit, although this may include some smaller desktop/laptop screens. In 'mobile' mode screen height is enforced and in desktop mode, only true window height is considered. You can use a third party deivce detection script to apply the best setting.
293 |
maxMobileHeight:
Default = 480, define the maximum initial window height at which a device is considered mobile. We recommend using a device detection script.
294 |
295 | 296 |

iOS Screen Height Issue

297 |

iOS subtracts the navigation bar from the window height, even if its hidden on page load. As a result only screen.height is a reliable measure for such devices.

298 |

Basic Usage

299 |

For basic usage when applying viewport height or width to CSS height or width properties, you need only add a comma separated string:

300 | 301 |
302 | 	 /* Exactly 80% of viewport height irrespective of page length
303 |     * most common use case, translates to 
304 |     * #my-element { height: 80vh; }
305 |     */
306 |     $('#my-element').viewportScale('80vh');
307 | 
308 | 309 |
    /* Exactly 50% of viewport height and 25% of viewport width 
310 |     * Translates to:
311 |     * #my-element { height: 50vh; width: 25vw; }
312 |     */
313 |     $('#my-element').viewportScale('50vh,25vw');
314 | 
315 | 316 |

For other supported combinations, use object notation:

317 | 318 |
    /* Height, width and font-size scaled to match viewport width only 
319 |     * Translates to:
320 |     * #my-element { max-height: 30vw; width: 20vw; font-size: 2vw; }
321 |     */
322 |     $('#my-element').viewportScale({
323 |         'max-height': '30vw',
324 |          width: '20vw',
325 |         'font-size': '2vw'
326 |     });
327 | 
328 | 329 |

HTML Snippet:

330 | 331 |
<section class="half-width-height">
332 |     <p> Scalable text 2% of viewport height or width, whichever is the largest</p>
333 | </section>
334 | 
335 | <section class="third-width-fixed-aspect">
336 |     <p> Fixed aspect ratio with font-size relative to screen width. </p>
337 | </section>
338 | 
339 | 
340 | 341 |

Stylesheet:

342 | 343 |
section.half-width-height {
344 |   position: relative;
345 |   width: 50vw; /* viewport width, not supported in IE8*/
346 |   height: 50vh; /* viewport height, not supported in IE8*/
347 |     border: dashed 3px #999999;
348 |     background-color: #ffff66;
349 |     margin: 5%;
350 | }
351 | 
352 | section.half-width-height p {
353 |   font-size: 2vmax;
354 | }
355 | 
356 | section.third-width-fixed-aspect {
357 |   position: relative;
358 |   width: 33.333vw; /* viewport width, not supported in IE8*/
359 |   height: 33.333vh; /* viewport height, not supported in IE8*/
360 |     border: dashed 3px #999999;
361 |     background-color: #9999ff;
362 |     margin: 5%;
363 | }
364 | 
365 | 
366 | 367 |

Javascript in jQuery context:

368 | 369 |
    
370 | /* Optionally include and instantiate viewportSize to add window.viewportSize.getWidth() method */
371 | 
372 | viewportSize.getWidth();
373 |     
374 | /* simple set up for only height and width using vh and vw units respectively */
375 | $('section.half-width-height').viewportScale('50vh,50vw');
376 | 
377 | /* For other units and combinations use object notation */
378 | $('section.half-width-height p').viewportScale({
379 |     'font-size': '2vmax'
380 | });
381 | 
382 | /* For other units and combinations use object notation */
383 | $('section.third-width-fixed-aspect').viewportScale({
384 |     'width': '33.333vw',
385 |     'height': '33.333vw',
386 | });
387 | 
388 | 389 |

Resize Events

390 | 391 |

The plugin responds to window resizing and changes in screen orientation. If you use this plugin within a resize event handler, you may want to disable this feature, by just adding {resize:false} in the options parameter.

392 | 393 |
394 | 			/* only set on initial page load  or in response to other triggers */
395 | 			$('#my-container').viewPortScale({'font-size': '3vw'}, {resize:false});
396 | 	
397 | 
398 | 399 |

Configure Browser Support Detection

400 | 401 |

The detection function temporarily creates an empty div, to which it applies a height of 100vh, a font-size of 2vh and in strict mode a width of 50vmax. After appending it to the body it checks its height matches the correct viewport height (outerHeight) and its font-size translated into pixels is approximately 1/50 of that. In strict mode it will detect vmax, which is not supported in Internet Explorer 9-11. In basic mode, where only vw and vh units are required, IE9 to 11 should pass the test.

402 |

By contrast iOS Safari fails to support vh correctly and thus before version 8 failed both tests.

403 | 404 |

To suppress this test and always apply inline translated pixel-based styles, you may specify detect mode as the second options parameter of viewportScale(). When using simplified string syntax in the first parameter, the plugin will only run a basic test e.g.

405 | 406 |
407 | 			/* Apply basic test only, as vmax and vmin are not required */
408 | 			$('#my-container').viewPortScale(
409 | 					{
410 | 						'font-size':
411 | 						'3vw'
412 | 					},
413 | 					{
414 | 						detect:'basic'
415 | 					}
416 | 				);
417 | 	
418 | 
419 | 420 |
421 | 			/* Always apply irrespective of browser support, skip browser detection */
422 | 			$('#my-container').viewPortScale(
423 | 				{
424 | 					'font-size': '3vw'
425 | 				},
426 | 				{
427 | 					detect:'skip'
428 | 			});
429 | 	
430 | 
431 | 432 |
433 | 434 | 514 | 515 | 516 | -------------------------------------------------------------------------------- /dist/viewport-scale.js: -------------------------------------------------------------------------------- 1 | /* viewportScale v0.5.1 | Author: Neil Gardner, 2014 | License: MIT/GPL */ 2 | (function($) { 3 | 4 | $.fn.viewportScale = function(units,options){ 5 | 6 | var element = this, 7 | numEls = 0, 8 | vhSupported = false, 9 | ww = 0, 10 | wh=0, 11 | wmin=0, 12 | wmax=0, 13 | props={}, 14 | unitRgx = new RegExp('\\b(\\d+(\\.\\d+)*)\\s*(v([wh]|max|min))'), 15 | supported = false, 16 | _gauged = false; 17 | 18 | var settings = $.extend({ 19 | resize: true, // respond to window resize / orientation change events 20 | detect: 'full', // full | basic | strict full = detect vmax/vmin support, basic = only vw/vh support | scrict = enforce full compliance even if vmax not specified 21 | sizeMode: 'auto', // auto|mobile|desktop Determines method used to gauge viewport height, for desktop window.height without status bars, for mobile screen.height. In auto mode initial 22 | maxMobileHeight: 480 // max window height at which a device is considered mobile in auto mode 23 | }, options ); 24 | 25 | var detectSupport = function() { 26 | var b = $('body'); 27 | if (b.hasClass('vh-checked') == false) { 28 | var div = $('
'),className = 'vh-checked'; 29 | gaugeWindowSize(); 30 | _gauged = true; 31 | if (div.length>0) { 32 | if (typeof units == 'string' && settings.detect != 'strict') { 33 | settings.detect = 'basic'; 34 | } 35 | b.append(div); 36 | var attrs = {position:'fixed',height:'100vh','font-size':'2vh',width:'50vmax','z-index':-2000,padding:0}, ds=0; 37 | div.css(attrs); 38 | ds = div.outerHeight(); 39 | supported = ds > (wh * 0.85) && ds < (wh * 1.15); 40 | if (supported) { 41 | ds = div.css('font-size'),fract = 0; 42 | if (ds) { 43 | ds = ds.replace(/[a-z]/g,''); 44 | if ($.isNumeric(ds)) { 45 | ds = ds - 0; 46 | fract = (wh / ds); 47 | supported = (fract > 42.5 && fract < 52.5); 48 | if (supported) { 49 | className += ' vh-supported'; 50 | } 51 | if (settings.detect != 'basic' && supported) { 52 | ds = div.outerWidth(); 53 | supported = ds > ((wmax / 2)*0.95) && ds < ((wmax / 2)*1.05); 54 | if (supported) { 55 | className += ' vmax-supported'; 56 | } 57 | } 58 | } 59 | } 60 | } 61 | div.remove(); 62 | b.addClass(className); 63 | } 64 | } else { 65 | supported = settings.detect == 'basic'? b.hasClass('vh-supported') : b.hasClass('vmax-supported'); 66 | } 67 | } 68 | 69 | // Fetch window size on initial page load and subsequent resizing 70 | var gaugeWindowSize = function() { 71 | // support for ViewportSize plugin 72 | var flipOrient = false; 73 | if (window.orientation) { 74 | flipOrient = Math.abs(window.orientation%180) >= 45; 75 | } 76 | if (settings.sizeMode != 'mobile') { 77 | if (window.viewportSize) { 78 | ww = window.viewportSize.getWidth(); 79 | } else { 80 | ww = $(window).outerWidth(); 81 | } 82 | if (window.innerHeight) { 83 | wh = window.innerHeight; 84 | } else { 85 | wh = document.documentElement.clientHeight; 86 | } 87 | if (settings.sizeMode == 'auto' && wh <= settings.maxMobileHeight) { 88 | settings.sizeMode = 'mobile'; 89 | } 90 | } 91 | if (settings.sizeMode == 'mobile') { 92 | if (flipOrient) { 93 | ww = screen.height; 94 | wh = screen.width; 95 | } else { 96 | ww = screen.width; 97 | wh = screen.height; 98 | } 99 | } 100 | //wh = (window.innerHeight + wh) / 2 101 | 102 | if (wh > ww) { 103 | wmax = wh; 104 | wmin = ww; 105 | } else { 106 | wmax = ww; 107 | wmin = wh; 108 | } 109 | } 110 | 111 | // Translate percent value to a window-size based pixel unit 112 | var translatePc = function(pc,wUnit) { 113 | if ($.isNumeric(pc)) { 114 | return Math.ceil((pc/100) * wUnit) + 'px'; 115 | } 116 | return false; 117 | } 118 | 119 | // Calculate size based on window height and/or width 120 | var resetSize = function(){ 121 | var attrs={},prop, u, ws; 122 | if (!_gauged) { 123 | gaugeWindowSize(); 124 | } 125 | for (key in props) { 126 | prop = props[key]; 127 | ws = false 128 | if ('none' != prop.unit) { 129 | switch (prop.unit) { 130 | case 'vw': 131 | ws = ww; 132 | break; 133 | case 'vh': 134 | ws = wh; 135 | break; 136 | case 'vmax': 137 | ws = wmax; 138 | break; 139 | case 'vmin': 140 | ws = wmin; 141 | break; 142 | } 143 | if ($.isNumeric(ws)) { 144 | attrs[key] = translatePc(prop.num,ws); 145 | } 146 | } 147 | } 148 | _gauged = false; 149 | element.css(attrs); 150 | } 151 | 152 | // Match units, vw, vh, vmax or vmin with integer or float numerals 153 | var matchUnit = function(str) { 154 | var prop = {unit: 'none',num:null}; 155 | if (str.length>1) { 156 | var match = str.match(unitRgx); 157 | if ($.isNumeric(match[1])) { 158 | switch (match[3]) { 159 | case 'vw': 160 | case 'vh': 161 | case 'vmin': 162 | case 'vmax': 163 | prop.unit = match[3]; 164 | prop.num = match[1] - 0; 165 | break; 166 | } 167 | } 168 | } 169 | return prop; 170 | } 171 | 172 | var apply = function() { 173 | var valid = false; 174 | if (typeof units == 'string') { 175 | units = units.toLowerCase(); 176 | var parts = units.split(','),i=0,prop; 177 | for (; i < parts.length;i++) { 178 | if (parts[i].length>1) { 179 | prop = matchUnit(parts[i]); 180 | switch (prop.unit) { 181 | case 'vw': 182 | props.width = prop; 183 | valid = true; 184 | break; 185 | case 'vh': 186 | props.height = prop; 187 | valid = true; 188 | break; 189 | } 190 | } 191 | } 192 | } else if (typeof units == 'object') { 193 | var strVal,prop; 194 | for (key in units) { 195 | strVal = units[key]; 196 | switch (key) { 197 | case 'width': 198 | case 'height': 199 | case 'top': 200 | case 'bottom': 201 | case 'left': 202 | case 'right': 203 | case 'min-width': 204 | case 'max-width': 205 | case 'min-height': 206 | case 'max-height': 207 | case 'font-size': 208 | prop = matchUnit(strVal); 209 | if (prop.unit != 'none') { 210 | props[key] = prop; 211 | valid = true; 212 | } 213 | break; 214 | } 215 | } 216 | } 217 | if (valid) { 218 | resetSize(); 219 | if (settings.resize !== false) { 220 | $(window).on('resize.viewport orientationchange.viewport',resetSize); 221 | } 222 | } 223 | } 224 | 225 | // Set up for all matched elements 226 | var init = function() { 227 | numEls = element.length; 228 | if (numEls>0) { 229 | if (settings.detect != 'skip') { 230 | detectSupport(); 231 | } 232 | if (!supported) { 233 | apply(); 234 | } 235 | } 236 | } 237 | 238 | // initialise 239 | init(); 240 | 241 | // return self for chaining 242 | return this; 243 | } 244 | 245 | })(jQuery); -------------------------------------------------------------------------------- /dist/viewport-scale.min.js: -------------------------------------------------------------------------------- 1 | /* viewportScale v0.5.1 | Author: Neil Gardner, 2014 | License: MIT/GPL */ 2 | (function($){$.fn.viewportScale=function(units,options){var element=this,numEls=0,vhSupported=false,ww=0,wh=0,wmin=0,wmax=0,props={},unitRgx=new RegExp("\\b(\\d+(\\.\\d+)*)\\s*(v([wh]|max|min))"),supported=false,_gauged=false;var settings=$.extend({resize:true,detect:"full",sizeMode:"auto",maxMobileHeight:480},options);var detectSupport=function(){var b=$("body");if(b.hasClass("vh-checked")==false){var div=$("
"),className="vh-checked";gaugeWindowSize();_gauged=true;if(div.length>0){if(typeof units=="string"&&settings.detect!="strict"){settings.detect="basic"}b.append(div);var attrs={position:"fixed",height:"100vh","font-size":"2vh",width:"50vmax","z-index":-2e3,padding:0},ds=0;div.css(attrs);ds=div.outerHeight();supported=ds>wh*.85&&ds42.5&&fract<52.5;if(supported){className+=" vh-supported"}if(settings.detect!="basic"&&supported){ds=div.outerWidth();supported=ds>wmax/2*.95&&ds=45}if(settings.sizeMode!="mobile"){if(window.viewportSize){ww=window.viewportSize.getWidth()}else{ww=$(window).outerWidth()}if(window.innerHeight){wh=window.innerHeight}else{wh=document.documentElement.clientHeight}if(settings.sizeMode=="auto"&&wh<=settings.maxMobileHeight){settings.sizeMode="mobile"}}if(settings.sizeMode=="mobile"){if(flipOrient){ww=screen.height;wh=screen.width}else{ww=screen.width;wh=screen.height}}if(wh>ww){wmax=wh;wmin=ww}else{wmax=ww;wmin=wh}};var translatePc=function(pc,wUnit){if($.isNumeric(pc)){return Math.ceil(pc/100*wUnit)+"px"}return false};var resetSize=function(){var attrs={},prop,u,ws;if(!_gauged){gaugeWindowSize()}for(key in props){prop=props[key];ws=false;if("none"!=prop.unit){switch(prop.unit){case"vw":ws=ww;break;case"vh":ws=wh;break;case"vmax":ws=wmax;break;case"vmin":ws=wmin;break}if($.isNumeric(ws)){attrs[key]=translatePc(prop.num,ws)}}}_gauged=false;element.css(attrs)};var matchUnit=function(str){var prop={unit:"none",num:null};if(str.length>1){var match=str.match(unitRgx);if($.isNumeric(match[1])){switch(match[3]){case"vw":case"vh":case"vmin":case"vmax":prop.unit=match[3];prop.num=match[1]-0;break}}}return prop};var apply=function(){var valid=false;if(typeof units=="string"){units=units.toLowerCase();var parts=units.split(","),i=0,prop;for(;i1){prop=matchUnit(parts[i]);switch(prop.unit){case"vw":props.width=prop;valid=true;break;case"vh":props.height=prop;valid=true;break}}}}else if(typeof units=="object"){var strVal,prop;for(key in units){strVal=units[key];switch(key){case"width":case"height":case"top":case"bottom":case"left":case"right":case"min-width":case"max-width":case"min-height":case"max-height":case"font-size":prop=matchUnit(strVal);if(prop.unit!="none"){props[key]=prop;valid=true}break}}}if(valid){resetSize();if(settings.resize!==false){$(window).on("resize.viewport orientationchange.viewport",resetSize)}}};var init=function(){numEls=element.length;if(numEls>0){if(settings.detect!="skip"){detectSupport()}if(!supported){apply()}}};init();return this}})(jQuery); 3 | -------------------------------------------------------------------------------- /dist/viewportSize-min.js: -------------------------------------------------------------------------------- 1 | /*! viewportSize | Author: Tyson Matanich, 2013 | License: MIT */ 2 | (function(n){n.viewportSize={},n.viewportSize.getHeight=function(){return t("Height")},n.viewportSize.getWidth=function(){return t("Width")};var t=function(t){var f,o=t.toLowerCase(),e=n.document,i=e.documentElement,r,u;return n["inner"+t]===undefined?f=i["client"+t]:n["inner"+t]!=i["client"+t]?(r=e.createElement("body"),r.id="vpw-test-b",r.style.cssText="overflow:scroll",u=e.createElement("div"),u.id="vpw-test-d",u.style.cssText="position:absolute;top:-1000px",u.innerHTML="