Dr Derek Bridge
School of Computer Science & Information Technology
University College Cork
Lecture Objectives
learn the principles of responsive layout
learn how to use CSS media queries for responsive layouts
learn to solve the problems caused by images in responsive layouts
Warning
Fog of details ahead!
Do not 'learn off'.
Look-up when needed.
Responsive Web Design (RWD)
In RWD, we adapt the layout to the characteristics of the window/device.
Responsive Components
Some of the things we have seen so far are already helpful for RWD.
Liquid layouts, using relative units or percentages.
Flexbox, assuming, e.g. we allow items to wrap and to flex.
Grid layout, if we use, e.g., repeat(auto-fill, 20em)
When these do not suffice, then use media queries.
CSS Media Queries
body {
color: white;
background-color: black;
}
@media screen and (min-width: 600px) {
body {
background-color: red;
}
}
@media screen and (min-width: 800px) {
body {
background-color: blue;
}
}
@media screen and (min-width: 1000px) {
body {
background-color: yellow;
}
}
Use a black background.
But, if the viewport is at least 600px, use a red background.
But, if the viewport is at least 800px, use a blue background.
But, if the viewport is at least 1000px, use a yellow background.
Media Queries
@media screen and (min-width: 800px) {
…
}
Simple media queries comprise:
the media type: e.g. screen
an expression containing a media feature (e.g. min-width) and a value (e.g. 800px) in parentheses; and
some CSS between curly braces.
In liquid layouts, you don't know how much space is available for your images.
If the image is wider than the available space, it will overflow its container.
In liquid layouts, we will have to allow the browser to scale the image.
Images for Liquid Layouts
Responsive Web Design recommends we set the max-width to 100% in the CSS:
img {
max-width: 100%;
}
If the image is narrower than its container, it will display at its normal size.
If it is wider than its container, it will be scaled down to match the width of the container.
Or you could set the width to 100%:
img {
width: 100%;
}
Then the image scales up or down to match the container.
But There Are Still Problems
resolution switching problem
you want to serve smaller image files to narrow screen devices, and also optionally you want to serve different resolution images to high density/low density screens
art direction problem
you want to serve different images for different layouts — for example a wide image showing a full scene for a desktop layout, and a narrower, cropped image showing a close-up for a mobile layout
Resolution Switching
HTML solves this using the srcset and sizes attributes, e.g.: