Saturday, October 25, 2014

Responsive Div to Display Content with a Responsive Background Image

So, I wanted to be able to display a responsive image that dynamically displays content depending on the winner of a contest. I have an image called 'Winner of the Week' where a post is displayed congratulating the Winner of a Weekly contest.

I'm using the shortcodes ultimate plugin to display the most recent post tagged "Winner of the Week" within a div that is styled to be centered with a cool background image. It presented a couple of coding challenges that I wanted to share solutions for.

First, I needed the background image to be responsive (as the div resized the background image was not resizing and so not all of the image was displaying). I found a solution to that on stack overflow here. The image below is the CSS code I needed:


Second, I needed the content inside the post to remain within the background image. For this I needed the div containing both the post and the background image to maintain a constant aspect ratio. I was able to find a solution for this on stack overflow as well. This one involves using two divs (one position: relative; and one position: absolute;) with a combination of width and padding-bottom (as a percentage) to create a fixed aspect ratio. The thread has more details here and there's also a link to a demo so you can watch it in action here.


If you'd like to see how I got this all to come together, you can visit the fiddle where I've shared the code here. To see my code in action, click on the photo below:


No comments:

Post a Comment