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

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

php Use cURL and the DOM to extract content with specified CSS styling

Unclear in the title, I want to copy all content from a specific div on an existing webpage (not owned by me). The code successfully extracts the content. Extractor code: // Get Data $curl_handle=curl_init(); curl_setopt($c ...

SSR with Material UI Drawer encounters issue during webpack production build meltdown

When I attempted to utilize the Material UI SSR example provided by Material-UI (Link), it worked successfully. However, my next step was to integrate the Material-UI Drawer into this example. To do so, I utilized the Persistent drawer example code also pr ...

The sticky navigation bar becomes fixed at the top prematurely

Having a sticky navbar on my Bootstrap-based website, I've implemented the following jQuery code: $(document).ready(function () { var flag = false; function stickNav() { $(".navbar-default").affix({ o ...

Can ng-submit be overridden?

Is there a way to modify ng-submit in order to execute certain functions before running the expression it contains? For instance, I want to: 1) Mark all fields as dirty or touched so that validation is performed on all fields, even if the user skipped som ...

The regex string parameter in node.js is not functioning properly for matching groups

The String.prototype.replace() method documentation explains how to specify a function as a parameter. Specifying a string as a parameter The replacement string can contain special patterns for inserting matched substrings, preceding and following portion ...

What could be causing the vertical alignment issue of this logo in its parent container?

I am having an issue with the vertical centering of the logo element within the <header> container on this page. It seems to be more pronounced on mobile devices compared to desktop. However, the second element (#forum-link) is aligning correctly. W ...

Angular: Clicking on a component triggers the reinitialization of all instances of that particular component

Imagine a page filled with project cards, each equipped with a favorite button. Clicking the button will mark the project as a favorite and change the icon accordingly. The issue arises when clicking on the favorite button causes all project cards to rese ...

Error in Laravel Mix Vuejs component: Syntax problem detected in <template />

My development environment involves Windows 10 OS and I have created a Laravel 8 project integrated with VueJs. However, when I try to access the file ./components/app.vue, it returns a SyntaxError: Unexpected token (1:0) The content of the app.vue file i ...

The styling of Div remains unchanged by CSS

Currently, I am working on a website using HTML and CSS. I have created a division element and applied a class to it called profile_pic. However, when I make changes to this class in the CSS file, it does not reflect on the div. It seems like the styling ...

Populate the content within a div element with specified height and width by utilizing JavaScript and jQuery

I need help with filling a fixed height div with long text retrieved via ajax in json format. For example, if I have a div with a height of 500px and width of 300px, with a font size of 16px. Is there a javascript recursive method that can fill the data ...

The onClick event is not functioning properly with React's select and option elements

Looking for a way to get the option value from each region? const region = ['Africa','America','Asia','Europe','Oceania']; <div className="options"> <select> ...

Clearing local storage in JavaScript after a certain period of time

On my signup page, I have divided the process into 5 stages and am using the user ID to track which stage they are at by storing it in local storage. However, I would like to automatically remove the ID from local storage if users leave my website without ...

Having trouble selecting a button using xpath in Scrapy Python?

I am currently attempting to scrape quotes from a website called using my spider code that looks something like this: class quote(scrapy.Spider): name = 'quotes' # defining Name start_urls = [''] # Targeted urls def parse(s ...

Enhancing security in client-server communication using HTML5 Ajax

Thank you for your assistance today. I am currently in the process of developing an HTML5 game and require guidance on the most effective method for Client Server communications. I am exploring alternatives to socket.io for undisclosed reasons. The key p ...

Changing Images with Jquery on Click Event

This section of the HTML document contains an image link that is designed to switch between two images when clicked. The images in question are timeline-hand and hand-clicked. Clicking on the image should change it from one to the other and vice versa. Ho ...

Discovering the technique to dynamically load various content using jQuery in a div based on its

After discovering this code to extract information from the first div with an id of container (box4) and retrieve any new data from the URL, everything was functioning correctly. However, I encountered an issue when attempting to load box5 and rerun the co ...

Tips for adjusting the size of a dropdown arrow icon

Is there a way to adjust the size of the drop-down icon using CSS? If not, I am looking to replace it with an image button. Thank you! <select> <option value="age">18</option> <option value="age"& ...

Error: Attempting to assign a value to 'onclick' property of null object [Chrome Extension]

window.onload = function() { document.getElementById('item_save').onclick = function() { var item_name = document.getElementById('item_name').value; var item_size = document.getElementById('item_size').value; v ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...