Is there a way to create this dynamic design without relying on JavaScript?

I am attempting to achieve a specific design without relying on JS, a demonstration can be viewed at jsfiddle.net/k2h5b/.

Essentially, I want to showcase two images, both centered, one as the background and one as the foreground:

  • Background Image: Should take up the entire window while maintaining aspect ratio, resulting in the image always touching two opposite edges of the window with cropping.
  • Forground Image: Should be contained within the window while preserving aspect ratio, meaning the image will always touch two opposite edges of the window without being cropped.
  • Whether it's a <div> or an <img> tag doesn't matter, as long as they display the images accordingly.
  • Assume that the image sizes are known beforehand and can be utilized in the CSS or HTML sections.

My inquiry is: can this layout be achieved using solely CSS or CSS3?

If it's not feasible, I am open to suggestions that come close to my objective.

Examples:

  • Illustration of the background image cropped from the top and bottom:

  • Representation of the background image when cropped from the left and right:

Answer №1

After reviewing the response from @Kent Brewster, I believe that all of the OP's requirements can be met.

This solution avoids the issue of the foreground image being cropped and allows for a constant margin around it. Instead of using an img tag, we utilize a div due to the use of background images. You can find the live example at this link, along with the following code snippet:

<div id='bg'></div>
<div id='fg'></div>

#bg {
  position: absolute;
  height: 100%;
  width: 100%;
  background-image: url(http://i.imgur.com/iOvxJ.jpg);
   background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: cover;
}
#fg {
  position: absolute;
  top: 10px;
  left: 10px;
  bottom: 10px;
  right: 10px;
  opacity: .7;
  background-image: url(http://i.imgur.com/HP9tp.jpg);
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-size: contain;
}

Answer №2

Give this a shot:

<html>
<style>
body {
  margin: 0;
}
#bg {
  position: absolute;
  height: 100%;
  width: 100%;
  background: transparent url(bg.jpg) 50% 50% no-repeat;
  background-size: cover;
}
#fg {
  position: absolute;
  height: 90%;
  width: 90%;
  top: 5%;
  left: 5%;
  background: transparent url(fg.jpg) 50% 50% no-repeat;
  background-size: cover;
  opacity: .7;
}
</style>
<body>
<div id="bg"></div>
<div id="fg"></div>
</body>
</html>

If the scaling requirement is adjustable, it could be effective. Check out http://jsfiddle.net/k2h5b/5/ to view it in action.

Answer №3

Absolutely, it can be done.

Essentially, what I did was set the background image as the background for the <body> element (although it doesn't have to be specifically the body), and then inserted the image inside with a slight margin.

<body>
  <img id='fg' src='http://3.bp.blogspot.com/-OYlUbWqyqog/TeL-gXGx3MI/AAAAAAAAHRc/bdqvvvaeC7c/s1600/bald-eagle3.jpg'></img>
</body>

css:

body {
  margin: 0; padding: 0;
  overflow: hidden;
  background: url('http://wallpaper.zoda.ru/bd/2006/07/21/2c7b4306fd22f049f331d43adb74a5f7.jpg') no-repeat left top;
}

#fg {
  margin: 20px 20px;
  opacity: 0.7;
}

If the window size is too large, there may be some issues. One approach could be using media queries to fetch different image sizes based on the window dimensions.

edit — If you wish for the image to crop and maintain the correct aspect ratio, knowing the image size beforehand could be crucial. Without that information, here's another alternative option.

<body>
  <div id='fg'>&nbsp;</div>
</body>

css:

body {
  margin: 0; padding: 0;
  overflow: hidden;
  background: url('http://wallpaper.zoda.ru/bd/2006/07/21/2c7b4306fd22f049f331d43adb74a5f7.jpg') no-repeat left top;
}

body, html { width: 100%; height: 100%; }

#fg {
  margin: 2%; width: 96%; height: 96%;
  opacity: 0.7;
  background: url('http://3.bp.blogspot.com/-OYlUbWqyqog/TeL-gXGx3MI/AAAAAAAAHRc/bdqvvvaeC7c/s1600/bald-eagle3.jpg') no-repeat center center;
}

If you are aware of the image dimensions, setting max-height and max-width could be beneficial. (I will experiment with that as well :-)

another edit To ensure the background crops in a centered manner, adjusting the position to "center center" instead of "left top" might be necessary. (Or "center top" if horizontal centering is sufficient.)

Vertically centering elements using CSS without advanced non-standard features like flexbox is challenging. JavaScript might be required for such tasks. It's worth noting that utilizing JavaScript solutions can significantly slow down the browser. A possible workaround is introducing a slight delay before recalculations occur, ensuring CPU efficiency during window resizing events.

further update @Kent Brewster's suggestion for vertical centering is excellent - that trick always slips my mind :-)

Answer №4

It is impossible to achieve this particular visual effect using CSS alone, primarily due to two key reasons:

  1. When attempting to resize an image, the background property cannot be utilized, necessitating the use of an <img> tag instead. Without setting specific width and height parameters, the image will automatically expand to fill available space, potentially distorting the aspect ratio or causing cropping.
  2. Another challenge in resizing images is achieving vertical alignment at the center of the page without precise knowledge of its dimensions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a pop-up upon clicking an image or button

My goal is to create a popup that collects emails when someone interacts with an image as if it were a button. In my footer.php file, I have included the following code (with placeholders for privacy reasons): <script> function showMailingPopUp() { ...

What are the best practices for utilizing intro.js effectively on mobile devices?

Description When using introjs on mobile devices with a screen width of less than 600px, the tooltip ends up covering the element. When I hold the device horizontally, the tooltip adjusts its position accordingly. I attempted to apply custom CSS to the too ...

Implementing jQuery's live() method to handle the image onload event: a guide

Looking to execute a piece of code once an image has finished loading? Want to achieve this in a non-intrusive manner, without inline scripting? Specifically interested in using jQuery's live() function for dynamically loaded images. I've attemp ...

How can I divide a div by utilizing word wrap?

My CSS-styled div is pretty straightforward .text { text-transform: capitalize; color: #FFFFFF; background: #918a8a; opacity: 0.6; font-size: 2em; height: 80px; width: 200px; } It creates a grey box w ...

Create a JavaScript timer on a PHP file that sets the input and textarea styles back to their default

When I use a timer in a JavaScript file after submitting a form to insert data into a MySQL database via PHP, the style of the textarea and input elements changes back to default. This issue only occurs when the timer is active. I tested submitting the fo ...

Ways to retrieve a variable from a separate TypeScript document

A scenario arises where a TypeScript script contains a variable called enlightenFilters$: import { Component, Input, OnInit } from "@angular/core"; import { ConfigType, LisaConfig } from "app/enrichment/models/lisa/configuration.model"; ...

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

Is there a way to switch the cursor to a pointer when hovering over a bar on a ChartJS bar graph?

Here's the chart I created: createChart = function (name, contributions, idArray) { globalIdArray = idArray; var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: "bar", data: { lab ...

Using the <a> </a> tag for navigating within the code logic

Currently, I am utilizing the <a> tag for clicking and navigating, as shown in the code snippet below. I am looking to navigate this code using the C# tag in the page_prerender event, based on the selected id. Can anyone offer assistance with this? ...

Convert your HTML document into a Microsoft Word file and see the total number of pages in

I have been experimenting with creating a Word document using HTML code. Thanks to various examples, I have made some progress. However, I am facing an issue where I cannot get the total number of pages to display as text on the first page of the document. ...

Issue with navigator.geolocation.getCurrentPosition not functioning again on Firefox

I've encountered a peculiar issue with JQuery that has me seeking assistance. On a certain page, I have the following block of javascript code. Upon initial page load, everything works smoothly. However, if the user navigates away and returns to the ...

Has the submit button become inactive once it has been inserted into a collapse?

I have recently implemented a collapse feature and inserted a form into it, but unfortunately, the submit buttons are not functioning properly. They are failing to send the data to the PHP file. <div class="container"> <div class= ...

Increased impact of dynamically added elements following page transition

After implementing dynamic functionality from jQuery in my code, I encountered an issue where if I navigate back one page and then return to the original page containing the added elements, they seem to trigger twice upon clicking. To troubleshoot, I incl ...

The Mui Switch track color fails to change when checked

I'm looking to customize the colors of the track for both checked and unchecked states. Currently, the track color is working for the unchecked state but defaults for the checked state: Checked State: https://i.stack.imgur.com/eGV4a.png Unchecked S ...

How to Switch between confirmation message boxes in an aspx.cs page

I am working on a search program that will scan a database for information. My goal is to notify users with a message if the date range exceeds 3 weeks, as searching through all the data might take some time. I have implemented a confirm message box in a ...

Building a sleek grid similar to Pinterest in Bootstrap v4.0 without relying on jQuery (using a black color scheme with equal width and varying height)

Is it feasible to craft a grid similar to Pinterest using Bootstrap 4? I am aware of the jQuery plugins that can be used, but is there a way to achieve this purely with CSS? Note: This is not a duplicate question. Please try to comprehend my query first ...

Responsive Bootstrap column with a fixed-width card

My Bootstrap-card is currently not adjusting its width properly. I want the card to occupy the full width of the column it's in. Below is a snippet of my code and a screenshot showing the current width along with the desired width indicated by a blue ...

Adjust the alignment of radio buttons in an HTML form based on the orientation of the device

As a newcomer to HTML and jQuery, I am currently working on an html form that will be used across multiple tablets. My goal is to have the available options displayed in two rows when the tablet is in portrait mode, like this: However, when the tablet is ...

What are the steps for specifically editing the mobile version of a website?

I am currently gaining experience by working on a website, but I am facing some challenges in making changes specifically for the mobile version. Here is an example: <h1 class="intro-header__title"> <span>Are you ready to</span> Expa ...

Creating a disappearing carousel on mobile and tablet that disappears when extended to md size

Currently, I am developing a website that consists of a .row with 3 columns at full size, each containing a bootstrap4 card. However, when the website is viewed on tablet or mobile devices, those 3 images should transform into a carousel display. I'm ...