jnystad.no About me

Easy Facebook cover photo positioning as the user intended it, with CSS only

Today's tip is simply how to use the cover photo information obtained via the Facebook Graph API to correctly position the photo the same way as the user intended, purely with CSS. This is important if you want to use their cover photo on some design or site feature, and respect their choice properly.

Facebook Graph API does not return a readily formatted variant of the cover photo. Instead you can obtain links to the original photo in various sizes. You also get one of two offset values that you must interpret properly to get the placement right.

The object returned when requesting a user with fields=cover looks something like this:

{
  "cover": {
    "id": 10000000000000,
    "source": "https://...jpg",
    "offset_y": 43,
    "offset_x": 22
  }
}

Source gives you a direct link to a pretty small version of the cover photo, which you can use directly if it's big enough for your purpose.

If not, you can request photo details by it's id, with fields=images to get a list of possible sizes to obtain.

The important part for positioning are the offset-variables. Both of them will not be present at a time, however, as only the dimension too big for the cover photo area can be adjusted. This usually means the vertical axis, since most photos have a lower aspect ratio than the narrow cover photo area, of 851 by 315 pixels.

Anyway, both should be handled to be safe.

The easiest way to get this right with CSS is by setting the image as a background image of a container, like this:

.cover {
  background-image: url('<source>');
  background-size: cover;
  background-position: (<offset_x> || 0)% (<offset_y> || 0)%;
  width: 851px;
  height: 315px;
}

The offset not present can be set to 0.

This will give you the exact same cover image section as on the desktop version of a Facebook profile page. Feel free to adjust size to fit, but if you change the aspect ratio of the area, it will look different.