Display a specific section of an image as the background in a div, with the image scaled and positioned perfectly

Utilizing a 1900 x 1080 image within a div as the background

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <style>
        html,body {
    height:100%;
}
        #imageHolder{
            background-size:100% auto;
            background-image:url(img/bg2.jpg);
            width:100%;
            height:30%;
        }
    </style>
</head>
<body>
    <div id="imageHolder"></div>
</body>
</html>

On my screen with dimensions of 1366x768, the complete width of the image is displayed while the height gets cropped. The current setup reveals only a portion of the image and I aim to maintain that specific section even when resizing the browser. Currently, any browser size adjustment results in both the div and image being resized, showcasing parts of the image that were initially hidden.

How can I ensure that the same section of the image remains visible, without any additional cropping or expansion, similar to when the browser window is maximized?

Answer №1

Below are some CSS properties that can be added to your style sheets:

background-repeat: no-repeat;
background-size: cover;

This snippet works well and is provided below.

html,body{
          height:100%;
          width:100%;
        }
        #imageHolder {
            width:100%;
            height:100%;
            /* background-image: url("https://i.stack.imgur.com/wwy2w.jpg");
            background-repeat:no-repeat; */
            background: url("https://i.stack.imgur.com/wwy2w.jpg") no-repeat center center fixed;
            background-size:cover;
            border:1px solid #000;
        }
<div id="imageHolder"></div>

Answer №2

background-repeat: no-repeat;
background-size: cover;
background-position: center center;

If you want to customize the background image position more precisely during resizing, you can use top, bottom, left, or right as alternatives to center center.

Answer №3

The initial layout provided has a ratio of height to width as follows:

768 window height * 30% height = 230 px (height)

230 px height / 1366 px width = 0.168

To maintain this ratio for the div, we can use the padding trick:

In this design, the top part of the image will always be visible, meeting your specified requirement.

If you wish to display another section of the image, you can adjust the background-position accordingly.

html,
body {
  width: 100%;
  margin: 0px;
}
#imageHolder {
  background-size: 100% auto;
  background-image: url(http://lorempixel.com/1900/1080);
  width: 100%;
  height: 0px;
  padding-top: 16.86%;
}
<div id="imageHolder"></div>

Answer №4

employ this

#imageHolder{
            background-image:url(img/bg2.jpg);
            width:100%;
            height:30%;
            background-size: cover;
        }

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

Issues with Bootstrap form functionality

I found inspiration on http://getbootstrap.com and decided to enhance it by including a hidden input. The file result.php contains $_REQUEST. Only the hidden value is visible to me. <form class="form-horizontal" role="form" action="/requests/result.p ...

Overflow of dropdown menus in HTML CSS

Hello, I am new to both html and stack overflow. Please forgive me if this question has already been asked, as I couldn't find anything (but maybe I didn't search enough?). I have tried using overflow and clear properties, but I am struggling to ...

I must eliminate any rows in a table that do not include the specified [string]

I have a task to remove specific rows from a table that do not contain a certain string. $(document).ready(function() { var str = "b"; $("#mytable tr td:not(:contains(str))").parent().remove(); }); //this approach is not produci ...

html code abruptly halted due to an unexpected termination of the file

I'm experiencing an issue with my senaraiperalatanstaf.php file. I inserted some PHP code in between, but now I'm getting a parse error indicating an unexpected end of the file. I've tried troubleshooting it without success. Any help would b ...

What is the process for attaching an iterator to the name value of every element within a cloneNode?

Consider the following scenario: <div id="addNewMenuElementPart2"> Numerous elements with a name attribute are present here. </div> <div id="addNewMenuElementPart3Optional"></div> Additionally, t ...

There was an error in React-Native using Native-base, as a failed prop type with an Invalid props.style key "NativeBase" was supplied to the "View"

Software Versions: React: 16.3.1 React-Native: ~0.55.2 Native-Base: ^2.8.0 Problem Alert: Warning: Failed prop type: Invalid props.style key 'NativeBase' supplied to 'View' Operating Systems: This warning keeps popping up in my r ...

Understanding how to read a JSON response when the dataType is specifically set to JSONP

I am attempting to send a JSONP request for cross-domain functionality. The issue is that my server does not support JSONP requests and interprets them as regular JSON, responding with an object: {result: 1} Below is the AJAX request I have made: jQuery. ...

A guide to integrating ffmpeg with NuxtJS

I am completely new to Nuxt and currently in the process of migrating a Vue application that generates gifs using ffmpeg.wasm over to Nuxt.js. However, every time I try to access the page, the server crashes with the following error message: [fferr] reques ...

Mastering the fundamentals of integrating/augmenting a fresh template in Umbraco

Let me be completely honest. Umbraco is unlike any other CMS I have worked with before. I am currently struggling to grasp the proper method of creating a Template and integrating it into Umbraco. How exactly can I add a template? I am making changes to t ...

Incorrect positioning of dropdown menu when using Bootstrap 4 and translate3d() function

Having multiple bootstrap 4.4.1 dropdown menus, each within a column which is functioning correctly except for the position calculation. Example of HTML col: <div class="container"> <div class="row"> <div class="col"> <div ...

Managing image downloads from a Node.js server: Tips and Best Practices

Currently, I am in the process of learning node.js and recently encountered a scenario where I need to download an image from the server by clicking a button on the webpage. I have set up an endpoint that receives two parameters: - The name of the image ...

Change from full manual control to automatic mode

Here is the link to my code: http://jsfiddle.net/yHPTv/2491/ I am experiencing an issue with the transition effect. The hidden element is supposed to slide into view from the right edge of the .block element, but instead, it just appears suddenly. .blo ...

What steps can you take to resolve the "TypeError: Cannot read property 'id' of undefined" issue?

I have been developing an app that involves using databases to add items for users based on their user ID, which is their username. However, whenever I attempt to add an item, I encounter an error that I can't seem to troubleshoot. The error message r ...

What is the best way to monitor different selections to keep track of their state?

In a certain scenario, a user is presented with three options: They can select the body_type of a car, the car_year it was manufactured, or the car_make. Initially, there is a state called carJson which contains a list of cars. "2": { " ...

The AJAX response shows a value of "undefined"

My HTML page contains these codes, which display a list of employees from the database. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script src="Scripts/jquery-1.10.2.js"></script> ...

Bringing in the jqGrid library with Meteor using NPM

I am currently working on a project using Meteor and I want to incorporate the free-jqgrid library. However, I am unsure of the correct way to import this library... I have tried: import 'free-jqgrid'; import jqGrid from 'free-jqgrid&apo ...

Execute an AJAX post request to the identical PHP page (utilizing the Jquery Form Plugin)

I am in the process of developing a new web interface using JavaTMP, an AJAX-based admin template. After spending time understanding its functionality, I have created a page with a form to allow users to create projects within my software. Typically, creat ...

Passing URL parameters from App.js to routes/index.js

I have a URL that looks like this: http://localhost:3000/?url=test In my Express application's app.js file, I'm attempting to extract the "test" parameter from the URL and pass it to my routes/index.js. Currently, I can easily send a static var ...

Error message "Invalid postback or callback argument" occurs when a button within a GridView, placed in an UpdatePanel, is clicked

I'm attempting to implement a jQuery confirm dialog that calls a web method. The dialog should be triggered when the delete button within a GridView in an UpdatePanel is clicked. However, upon clicking the button, I encounter an error stating "Invali ...

Retrieve the tweets from the next Twitter user in the Array using blogger.js

I am working on a project that involves a javascript array of Twitter usernames. Using blogger.js, I successfully load the first username along with their last 5 tweets. Now, I am looking to create HTML buttons or links for "previous" and "next" in order ...