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

Encountering Vue linting errors related to the defineEmits function

I am encountering an issue with the linting of my Vue SPA. I am using the defineEmits function from the script setup syntactic sugar (https://v3.vuejs.org/api/sfc-script-setup.html). The error messages are perplexing, and I am seeking assistance on how to ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Why do `setTimeout` calls within JavaScript `for` loops often result in failure?

Can you help me understand a concept? I'm not inquiring about fixing the code below. I already know that using the let keyword or an iffe can capture the value of i. What I need clarification on is how the value of i is accessed in this code snippet. ...

Embracing Divs Similar to the Grid Selector in Windows Phone

Can someone help me create square divs in HTML 5, similar to the example shown? I have written this HTML5 Code - what should I include in the CSS file to achieve the desired outcome? (If Bootstrap can be used, please provide the necessary classes instead ...

Having trouble with accessing input field in a modal that was generated by TinyMCE React within a Next.JS environment

In my current project, I am utilizing Next.JS and looking to incorporate the TinyMCE editor onto my webpage. Here is the code snippet I have implemented: <TinyMceEditor selector='textarea' initialValue={ props.value } apiKey=<AP ...

incorrect indexing in ordered list

I am facing an issue with the ngIf directive in Angular. My objective is to create a notification system that alerts users about any missing fields. Here's a stackblitz example showcasing the problem: https://stackblitz.com/edit/angular-behnqj To re ...

Can an array be used as valid JSON for a REST api?

Utilizing MongoDB with Mongoskin in a web application using Node.js allows for the execution of .find() on a collection to retrieve all documents within it. The result returned is a mongodb cursor. To convert this cursor into an Array, you can utilize the ...

Encountering an "undefined is not a function" error across all libraries

While working on ASP.Net MVC4, I have encountered an issue where I consistently receive the error message "undefined is not a function" when using jQuery functions with different libraries. Despite ensuring that every ID is correct and everything has bee ...

Dual-Language Dublin Core Metadata for Document Description

If I want to express the document title in two languages using Dublin Core, how can I do it? Based on my research, I could do the following: <meta name="dc.language" content="en"> <meta name="dc.language" content="fr"> <meta name="dc.title ...

What is causing the issue with my CSS keyframe animation not functioning correctly when using `animation-direction: reverse`?

Exploring the use of animation-direction: reverse to streamline my CSS keyframe animation process. An interesting scenario arises when a container div is clicked, toggling an "active" class using jQuery to trigger the animation in either forward or backwar ...

Vue data will remain inaccessible until the JSON.stringify() function is executed

Dealing with this problem is tricky for me as it involves complex behavior that I haven't encountered before in JavaScript or Vue.js. I aim to simplify the code to focus on the most crucial aspects. I utilize vue-class-component (6.3.2) to define my ...

The integration of Tinymce and Vuetify dialog is causing issues where users are unable to input text in the source code editor or add code samples

Having an issue with the Vuetify dialog and TinyMCE editor. Upon opening the dialog with the editor inside, certain functionalities like Edit source code or Insert code sample are not working as intended. Specifically, when attempting to use one of these p ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

Ways to increase the font size of input text using bootstrap's css framework

I currently have a bootstrap textbox set up like this: <input type="text" class="span9" required name="input_text"/> My goal is to increase the height of my input box to 300px. The width, on the other hand, is being handled by span9. I utilized In ...

In Snowflake, SQL error handling block fails to execute

Implementing error handling in Snowflake using a Try Catch block has been my focus. I've enclosed SQL queries within JavaScript for this purpose. However, upon executing the query, I noticed that it skips the Try Catch block and directly executes the ...

Issue with 1.bundle.js not loading during webpack production build with routing

I have been encountering an issue with my test repository for this specific problem (Link) It appears that the problem lies within the localization file, as I am using react-intl. The development version seems to be functioning properly. This is what&ap ...

What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure look ...

Attempting to send a formik form to a specified action URL

Seeking assistance with a simple fix as I navigate through the learning process. I have created an action called addTenant() that is supposed to receive the state and use it to dispatch a post API call, like so: export const addTenant = (tenant) => (di ...

'AngularJS' filtering feature

I am dealing with an array of objects and I need to extract a specific value when a key is passed in the 'filter' function. Despite my best efforts, the controller code snippet provided below returns an undefined response. Can someone please assi ...

What is up with this strange JavaScript variable string / DOM selection?

I'm facing a strange issue with a variable that appears to be a string when alerted, but in the console, it is actually a DOMSelection presented in tree form. How can I retrieve the actual string value from this console output? DOMSelection anchorNod ...