Skip to content
- Courses
- DSA to Development
- Newly Launched!
- Master Django Framework
- Become AWS Certified
- For Working Professionals
- Data Science Training Program
- JAVA Backend Development (Live)
- DevOps Engineering (LIVE)
- For Students
- Placement Preparation Course
- Data Science (Live)
- Master Competitive Programming (Live)
- GATE Exam Courses
- All Courses
- Tutorials
- Data Structures & Algorithms
- DSA for Beginners
- Data Structures
- Arrays
- Matrix
- Strings
- Linked List
- Stack
- Queue
- Tree
- Generic Tree
- Binary Tree
- Binary Search Tree
- AVL Tree
- B Tree
- B+ Tree
- Red Black Tree
- Tree Data Structure Tutorial
- Heap
- Hashing
- Graph
- Set Data Structure
- Map Data Structure
- Advanced Data Structure
-
-
- CSS Tutorial
- CSS Exercises
- CSS Interview Questions
- CSS Selectors
- CSS Properties
- CSS Functions
- CSS Examples
- CSS Cheat Sheet
- CSS Templates
- CSS Frameworks
- Bootstrap
- Tailwind
- CSS Formatter
Open In App
Last Updated : 25 Jan, 2024
Summarize
Comments
Improve
To resize an image or video to fit inside a div container, you can use the object-fit property. This property is used to specify how the content should fit inside the container. With object-fit, you can set the content to maintain its aspect ratio or stretch to fill the entire container. This allows you to control how the content is displayed within a specific div container.
Example 1: This example describes the auto-resize image fit to the div container. This example does not contain object-fit property.
html
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>To auto-resize an image</
title
>
<
style
>
body {
display: flex;
justify-content: center;
}
.geeks {
width: 60%;
See AlsoHow to make Images Responsive with Examples | BrowserStack HTML – Image Tag TutorialHow to Resize Images for Responsive Web DesignEverything You Need to Know about ID in CSSheight: 300px;
border: 1px solid #ccc;
}
img {
width: 100%;
height: 100%;
}
</
style
>
</
head
>
<
body
>
<
div
class
=
"geeks"
>
<
img
src
=
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"
alt
=
"Geeks Image"
/>
</
div
>
</
body
>
</
html
>
Output:
In the above example as the object-fit property is not used, the image is being squeezed to fit the container, and its original aspect ratio is destroyed.
Example 2: This example is used to display the part of image when use resize the div container.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>To auto-resize an image</
title
>
<
style
>
body {
display: flex;
justify-content: center;
}
.geeks {
width: 60%;
height: 300px;
border: 1px solid #ccc;
}
img {
width:100%;
height:100%;
object-fit:cover;
}
</
style
>
</
head
>
<
body
>
<
div
class
=
"geeks"
>
<
img
src
=
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"
alt
=
"Geeks Image"
/>
</
div
>
</
body
>
</
html
>
Output:
Note: Using object-fit: cover; will cut off the sides of the image, preserving the aspect ratio, and also filling in space.
Example 3: This example displays an image without using object-fit property. In this example, the size of the image is set manually and the image will not be able to maintain its aspect ratio and adjust or resize according to div container on resizing the browser window.
html
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
title
>Auto-resize of an image</
title
>
<
meta
charset
=
"UTF-8"
>
<
meta
name
=
"viewport"
content
=
"width=device-width, initial-scale=1.0"
>
<
style
>
body {
display: flex;
justify-content: center;
}
.container {
width: 400px;
height: 250px;
border: 1px solid #ccc;
overflow: hidden;
}
.container img {
width: 100%;
height: auto;
display: block;
}
</
style
>
</
head
>
<
body
>
<
div
class
=
"container"
>
<
img
src
=
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"
alt
=
"GeeksforGeeks Image"
>
</
div
>
</
body
>
</
html
>
See AlsoDifference betweenOutput:
Example 4: This example displays the part of image or image using object-fit property. In this example, the size of the image is set manually and the object-fit property is also used. In this case, on resizing the browser the image will maintain its aspect ratio and will not be resized according to div container.
html
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>To auto-resize an image</
title
>
<
style
>
body {
text-align: center;
}
img {
width: 400px;
height: 200px;
object-fit: cover;
}
</
style
>
</
head
>
<
body
>
<
img
src
=
"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png"
alt
=
"Geeks Image"
>
</
body
>
</
html
>
Output: Note: The property object-fit: cover; will cut the sides of the image, preserving the aspect ratio, and also filling in space.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
Previous Article
How to use a not:first-child selector in CSS?
Next Article
How to disable resizable property of textarea using CSS?
Please Login to comment...
Similar Reads
How to stretch div to fit the container ? A child div inside a container can be made to take the complete width and height of the parent div. There are two methods to stretch the div to fit the container using CSS that are discussed below: Method 1: The first method is to simply assign 100% width and 100% height to the child div so that it will take all available space of the parent div. E 2 min read How to Fit Background Image to Div using CSS ? In this article, we will see how to fit background images into HTML div. The main problem that is being solved here is that the dimensions of the background image of a div are not exactly the same as the dimensions of the actual div, so there arises a mismatch. Due to this mismatch, the background image doesn't fit properly in the div. Now, there a 3 min read How to Overlay/Hover Div in Flexbox Container Div? In CSS, overlay/hover effects can be achieved by using Flexbox containers to center content and applying styles to reveal overlays on hover. By positioning elements absolutely within a Flexbox container, overlays can cover the entire content area. These are the following approaches: Table of Content Using ::before Pseudo-elementUsing an Overlay Div 3 min read Auto-Fit vs Auto-Fill Property in CSS Grid CSS Grid is a powerful layout system that allows you to create complex, responsive layouts with ease. One of its key features is the ability to create a responsive layout without using media queries. Instead, you can use the grid-template-columns property, the repeat() function, and the auto-fit and auto-fill keywords to adjust the layout based on 4 min read How to Auto Resize Image in CSS FlexBox Layout and Keeping Aspect Ratio? In modern web design, responsive images are crucial to ensure that your site looks good on all devices. CSS Flexbox provides a powerful layout mode that allows you to create flexible and responsive layouts. We'll explore how to auto-resize images within a CSS Flexbox layout while maintaining their aspect ratio. ApproachDefine a div container with a 2 min read How to fit text container width dynamically according to screen size using CSS ? In this article, we have given a text paragraph and the task is to fit the text width dynamically according to screen size using HTML and CSS. Some of the important properties used in the code are as follows- display-grid: It helps us to display the content on the page in the grid structure.grid-gap: This property sets the minimum amount of gap bet 7 min read How to Set Div Width to Fit Content using CSS? The div can be managed to set the whole screen width or the width according to the need. In this article, we are going to discuss how can we set a div width to fit content using CSS. we will discuss different approaches and code examples. Below are the approaches to set div width to fit content using CSS: Table of Content Using Default CSSUsing inl 3 min read How to make CSS Font Size Fit Container Effectively ? Making CSS font size fit a container effectively involves ensuring that the text scales appropriately based on the dimensions of the container. This is crucial for maintaining readability and a consistent user experience regardless of the device being used. Table of Content Using ViewportUsing Media QueriesUsing CSS ClampUsing ViewportWe can use vi 5 min read How to position a div at the bottom of its container using CSS? Positioning a div at the bottom of its container means aligning the div so that it stays at the lowest point within the container's boundaries. This can be done using CSS techniques like absolute positioning, Flexbox, or Grid, each method providing different layout control options. Table of Content Using Absolute Positioning Using Flexbox Using Gri 3 min read How to resize SVG to fill its container in ReactJS? We can resize SVG to fill its container in ReactJS using the type props. We can add the following style to the SVG CSS Syntax: svg { width: inherit; height: inherit; } React Syntax: <svg style = {{ width: "inherit", height:"inherit"}} // Child elements </svg>Creating React Application: Step 1: Create a React application using the following 2 min read How to Make a Child Div Element Wider than Parent Div using CSS ? When the child div element has a fixed width that is wider than the parent div element, it will display overflow outside of the parent element. Because the overflow is hidden by default, one approach is to utilize the overflow attribute to enable it on an element. Another approach includes setting the position property of the parent div element to 2 min read How to overlay one div over another div using CSS Creating an overlay effect simply means putting two div together at the same place but both the div appear when needed i.e while hovering or while clicking on one of the div to make the second one appear. Overlays are very clean and give the webpage a tidy look. It looks sophisticated and is simple to design. Overlays can create using two simple CS 2 min read How to center elements in a div along a baseline without a container in CSS ? Centering elements in a div along a baseline without a container can be achieved using various approaches. In this article, we will discuss some of the approaches to achieve this and provide examples for the same. Method 1: Using Flexbox: One of the easiest ways to center elements along a baseline in a div is by using the Flexbox layout. We can use 4 min read How to make container shrink-to-fit child elements as they wrap? A Flexible Layout must have a parent element having display property set to flex. Direct child elements of the flexible container automatically become flexible items. Approach: The element below represents a flex container with four flex items. <div id="container"> <ul> <li>icecream</li> <li>sandwich</li 2 min read Create Image Resize App using Tailwind CSS Image Resizer is an application that is used to resize an uploaded image by providing new dimensions in the form of width and height. This application contains two numbered input fields to get the number input for width and height from the user. It also contains a file input field to upload an image file. It allows you to download the resized image 3 min read How to create auto-resize textarea using JavaScript/jQuery ? Textareas is the area for the input but the input size should be long. We can resize the input area. Create a textarea and the task is to automatically resize it when we type or paste the content in it. It can be achieved by using JavaScript and jQuery: Table of Content Using JavaScriptUsing jQueryMethod 1: Using JavaScriptTo change the height, a n 4 min read Image inside div has extra space below the image in CSS Sometimes when you insert an image inside a div element, you might notice that there is extra space below the image. This can happen due to various reasons such as the image having a different aspect ratio than the div, or the div having padding or margin that affects the image placement. In this article, we will discuss different approaches to sol 5 min read How to move a container inside of another container in Bootstrap 5 ? The container is used to set the content’s margin. It contains row elements and the row elements are containers of columns. This is known as the grid system. In this article, we will learn about How to move a container inside of another container in Bootstrap 5. We will move a container to the left in another container. Syntaxms-0 me-0 Table of Con 2 min read What is the Difference Between container and container-fluid in Bootstrap 5 ? In Bootstrap 5, the "container" class creates a responsive container with a fixed width, adjusting to different screen sizes while maintaining margins. On the other hand, the "container-fluid" class generates a full-width container that spans the entire viewport without any margins, providing a seamless layout across various devices. "Container" is 3 min read How to copy the content of a div into another div using jQuery ? Given an HTML document containing some div element and the task is to copy a div content into another div as its child using jQuery. There are two approaches to solve this problem that are discussed below: Approach 1: First, select the div element which needs to be copied into another div element.Select the target element where the div element is c 2 min read How to resize list style image in CSS ? In this article, we will learn to set an image or icon as the <li> image. We need to set the size of the custom list image to make it attractive. So, we will also learn the different ways to resize the custom list image. Syntax: In this article, we will use below CSS properties. background-image: We will add a custom image as a background ima 3 min read Resize image proportionally with CSS The resize image property is crucial for responsive web design, ensuring images automatically resize to fit their container. The max-width property in CSS is commonly used for this purpose. Note that the resize property won't work if the width and height of the image are defined in the HTML. Syntaximg { max-width:100%; height:auto; } Width can also 2 min read How to Rotate Container Background Image using CSS ? The CSS background-image property is used to add an image to the background of an element. In this article, the task is to rotate the image which is used in the background. Approach: The CSS transform property is used to apply two-dimensional or three-dimensional transformation to a element. This property can be used to rotate, scale, move or even 1 min read How to force child div to be 100% of parent div's height without specifying parent's height? When designing a website, you may want to create a layout where a child div element fills up the height of its parent div element. However, you may not know the exact height of the parent div element and you don't want to specify it. In this article, we will explore different approaches to force a child div element to be 100% of its parent div elem 3 min read How to center a div within another div? The div tag is used to construct a division or section of an HTML document in which other elements of HTML is placed and that division/section works like a container whose CSS styling can be done as a single unit or javascript can be used to perform various tasks on that container. Syntax: <div> <h3>'This is a div of the web page.>/h 4 min read How to center a div on the edge of another div in SASS ? In this article, we will see how to centre a div on the edge of another div using SASS. SASS is an extension of CSS that stands for Syntactically Awesome Style Sheets. It helps us to create things like variables, nested rules, etc. So that we can reuse the code. Centering a div on the edge of another div is not a difficult task. We can achieve it b 4 min read How to make Parent Div Activate Styling of Child Div for Hover and Active ? In this article, we will see how to make parent div activate styling of child div for hover and active. We can do this by using Pseudo-classes like hover and active. Approaches to make parent div activate styling of child div for hover and activeUsing Pure CSS: with pseudo-classesUsing CSS and JavaScript: without pseudo-classesMethod 1: Using Pure 2 min read How to make div fixed after scroll to that div ? In this article, we will see how to make a div fixed after you scroll to it by using the position property with a sticky value. This effect is generally used on websites when an important message needs to be shown. Set the property position to sticky to create elements that behave as fixed positions whenever the user scrolls to that position. Fixin 4 min read How to clear all div's content inside a parent div ? In this article, we are given an HTML document containing div elements and the task is to remove the existing HTML elements using jQuery. To accomplish this task, we can use the following methods: Table of Content jQuery remove() methodjQuery empty() methodjQuery html() methodjQuery remove() methodThe remove() method in jQuery is used to remove the 2 min read Create an Image Resize and Editor using React-Native Image manipulation in mobile apps is an important functionality, from cropping and resizing to adding filters or overlays. In this tutorial, you will learn the process of building a simple Image Resize and Editor application using React-Native. This project aims to provide a foundation to integrate image editing capabilities into their React-Native 3 min readArticle Tags :
- CSS
- Technical Scripter
- Web Technologies
- CSS-Questions
Trending in News
View More- How to Merge Cells in Google Sheets: Step by Step Guide
- How to Lock Cells in Google Sheets : Step by Step Guide
- #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
-
- Data Structures & Algorithms
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });