Tips for resizing a larger image to display only a specific portion in CSS (and incorporating JS if needed)

I need to resize an image that measures 1024x1024 and is segmented into 4 quadrants:

My goal is to reduce the size of this image so that quadrant 2 is 256x256 while masking out or hiding the remaining 3 quadrants, displaying only the desired section on the page. It should look like this:

Is it feasible to achieve this using CSS alone, or will JavaScript be required in the process?

Answer №1

If the browsers you are targeting support the background-size CSS property, you can achieve this effect using only CSS:

.bg {
    background-image: url(https://i.sstatic.net/HQaif.jpg);
    background-repeat: no-repeat;    
    background-size: 203%;
    background-position: top left; 
    width: 256px;
    height: 256px;  
}

To simplify future resizing, consider removing the red keyline between sections and setting the size property to 512px.

Check out this example fiddle for a demonstration.

For more information on background-size, visit this link.

Answer №2

UPDATE: included JavaScript and updated HTML

JS

$(document).ready(function() {
    $('#dyna').change(function() {
        $('#myBox').attr('class', 'box quad' + $('#dyna').val());
    });
});

HTML

<select id="dyna">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    </select>
<div id="myBox" class="box quad1"></div>
<!-- manually change the "quad" class number as needed-->

CSS

.box{
    background:url('https://i.sstatic.net/HQaif.jpg');
    width:512px;
    height:512px;
    background-size: 200%;
    background-repeat:no-repeat;
}

.quad1{
    background-position: 0% 0%;
}

.quad2{
    background-position: 100% 0;
}

.quad3{
    background-position: 0 100%;
}

.quad4{
    background-position: 100% 100%;
}

You can use JavaScript to dynamically change the "quad" class (quad1 to quad4)

View it in action: http://jsfiddle.net/EMKHJ/3/

Answer №3

To showcase a specific part of an image, try setting it as the background of an element and adjusting the background-position: 0px -30px;. Ensure the element's height and width match the desired quadrant size, then shift the quadrant into view with the CSS property background-position.

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

Difficulty in defining the header while using the submit hook in Remix 1.15

When I utilize the useSubmit hook to send a POST request, it appears that the header I specify is not being taken into account. Below is the code snippet for my submit function: submit('/dashboard/', { method: 'post', heade ...

What is the best way to arrange form inputs in a single row?

My form consists of three input boxes. While the first two inputs are single line, the third is a description field with 10 rows set as default. However, for some reason, this third box is not aligned properly with the other two. Please refer to the screen ...

The Google Apps spreadsheet script occasionally fails to complete iteration but functions properly in all other aspects

I have a script that goes through a spreadsheet of student data one row at a time to email students and their parents if the student's grade is below 60. The spreadsheet columns include: Student ID, Name, Email Address, Parent's Email Address, an ...

The JavaScript function exclusively reveals the final element, which is Three.js

I'm currently working on a fence generator function using Three.js, but for some reason, my function is only returning the last fence created. It's really puzzling to me... function createFence(nb){ var i; var position = -5; var loadingMan ...

What are the steps to modify the "text" displayed on a button in a kendo grid?

How can I change the default button text "add new record" on my kendo grid? I attempted to modify it using the following code, but it did not work: #turbinegrid .k-icon.k-add::after { content: "ADD"; } ...

What is the process for retrieving a JavaScript script generated by PHP through AJAX and executing the script successfully?

Utilizing the Google Maps API, I am in the process of creating my very own world. However, I have encountered a problem where the large number of markers/locations is causing the page to become unresponsive. I suspect that the solution lies in calling onl ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

Wait for AngularJS to load when the background image of a div becomes visible

Currently, I am utilizing the ng-repeat feature to fetch data from a $http.post request and then save it to the $scope.data variable. <div ng-repeat="key in [] | range:data.pages"> <div class="pageBackground" id="page_{{ (key+1) }}" ng-style= ...

Issue with Submit Button Functionality in Django Form Submission

I'm currently facing an issue with an HTML template I built using Bootstrap. My problem lies in the fact that I have a JavaScript function that dynamically adds rows to a Django form with specific fields whenever I need to. However, when I add a row, ...

What are the permissible child elements for an <a> tag?

Lately, I've been focused on structuring HTML code and it got me thinking about which elements are actually allowed as children of an <a> element. Can you help clarify? ...

Whenever I clear the contents of the datatable, I notice that 2 thead elements

I am facing an issue with a table that I populate using jQuery's .append() function and then initialize it as a datatable. Since the data is not fetched via an ajax call, I clear both the tbody and thead using .empty(). However, I encounter a problem ...

Having trouble making an Ajax request in Rails3

I am currently in the process of refactoring my project by incorporating AJAX functionality. I have a link that triggers an action in a controller: = link_to("Please work", "show_recent_chart", :remote => true) This links to a specific controller acti ...

Emphasize the engaged menu selection when the page is refreshed

My application is a dashboard app built with React, Redux, and Antdesign. I utilized the layout provided by Ant design at https://ant.design/components/layout/. One issue I encountered is that when clicking on side menus, the active menu gets bold but upo ...

Vue JS i18next: Handling Single Translation String Fallbacks

Recently, I've been utilizing i18next, and I decided to set a fallback value for some translated strings in case they are not available in the selected language. Here's an example: en: base.json "yes": "yes" "no": "no" fr: base.json ...

Tips for adjusting the material ui Popper width to fit the container without disabling the portal

Currently utilizing the material-ui popper library. I am trying to allow the popper to extend outside of its container in the vertical direction. To achieve this, I have set disableportal={false}. However, upon setting disableportal to false, when assign ...

JavaScript: Implementing a for loop to dynamically adjust CSS properties

How can I adjust the margin-top property of the ball element when clicking a button? Below is my current code, but it's not working as expected. Can you help? let ballMargin = ball.style.marginTop; moveButton.addEventListener('click', funct ...

Revise the if statement by using variables

Here is a function that already exists in a theme: function WShare( selector ) { var $this = $( selector ), $parent = $this.parent(); var opt = { url: window.location, text: document.title, }; if ( window.selectedText ) { ...

Using jQuery: The procedure for sending JSON data in an AJAX post request

Currently, I am working on AJAX where I have created a post request as shown below: $.ajax({ 'url':'http://localhost/api/create/', 'method':'POST', 'dataType': 'json', 'co ...

Identifying the camera model using getMediaStream

Are there methods available to determine if a user's device has a front, rear, or dual cameras installed? For instance, laptops typically only have a front-facing camera while some devices may have both. I am looking for a way to identify the type of ...

Ensure that the Left and Right menu are fixed in position, while allowing the middle content to be scrollable

I'm in the process of creating a web page with a fixed left and right menu, while the middle content should be scrollable and positioned behind the menus. I've attempted to implement this using the following HTML and CSS, but encountered an error ...