Creating a responsive photo gallery is tough. You need to calculate again and again and again. You're a web designer/developer and (face it) math is not your specialty. This Sass mixin allows you to add a simple bit of code in your stylesheet to dynamically calculate widths and margins for your photos.
Because every thing needs to be demonstrated. View the demo
Adaptable relies heavily on CSS selectors. You will need selectivizr.js to run this under Internet Explorer 7-8.
- Internet Explorer 9+
- Internet Explorer 7-8 (with selectivizr.js)
- Firefox 3.6+
- Chrome 9+
- Safari 4+
In your HTML, create a gallery using an unordered list. For example:
<!-- jQuery + Selectivizr adds support for nth-child in IE browsers 7-8 --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script src="scripts/selectivizr.js"></script> <!-- end selectivizr.js --><ul> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> <li><a href="#"><img src="images/beaker.png" /></a></li> </ul>
In your scss or sass document, add the grid mixin:
@mixin grid($items) { list-style: none; margin: 0; overflow: hidden; padding: 0; li { float: left; &:nth-child(1n) { margin: 5% 0 0 0; } @if $items > 1 { &:nth-child(1n) { margin: (5% / ($items - 1)) (5% / ($items - 1)) 0 0; } width: (95% / $items); *width: (94% / $items); } &:nth-child(#{$items}n) { margin-right: 0; } &:nth-child(-n+#{$items}) { margin-top: 0; } img, a { float: left; } a { text-align: center; width: 100%; } } }
Next, apply the mixin to your containing unordered list and specify how many images should be in each row. For example:
ul { @include grid(4); }
Done.
When you are in a media query, you can now readjust your gallery to include fewer or more images. For example:
@media (max-width: 768px) { ul { @include grid(3); } }
- Fixed a numerous amount of browser issues
- Enhanced documentation
- Added selectivizr.js to support earlier versions of IE
- Initial release. Hooray!