What is the best way to reveal a hidden section of an image contained within a div with a fixed height, using only CSS?

I have a container div that is 150x150 in size and contains an image that is 150x180 in size. The div has the CSS property overflow: hidden enabled, so part of the image is not visible. While the div size is fixed at 150x150, the height of the image may vary from one image to another. When hovering over the div or the image, I want to vertically move the image so that the hidden portion becomes visible to the viewer.

To achieve this functionality, I have used jQuery. Below are the snippets of my CSS, HTML, and jQuery code:

$("#container").mouseenter(function() {
    img_height = $(this).find('img').height();
    $(this).find('img').animate({
        'top': 150 - img_height
    }, 300);
});

$("#container").mouseleave(function() {
    $(this).find('img').animate({
        'top': 0
    }, 300);
});
#container {
    width: 150px;
    height: 150px;
    overflow: hidden;
    border: 1px solid;
    position: relative;
}
#container img { 
    position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
    <img class="fl" src="http://media.dcentertainment.com/sites/default/files/superman-150x180.jpg" width="150"/>
</div>

Is it possible to achieve the same functionality using CSS transitions? If yes, how can it be done?

Answer №1

Consider this approach. The key idea is to adjust the initial vertical offset in the style attribute as the image loads.

<img onload="this.style.bottom = '' + (150 - this.offsetHeight) + 'px' src="..." />

However, please note that this solution involves a mix of HTML and CSS.

.container {
    width: 150px;
    height: 150px;
    position: relative;
    overflow: hidden;
}

.container img {
    position: absolute;
    transition: bottom 0.3s;
}

.container img:hover {
    bottom: 0 !important;
}
<div class="container">
    <img src="http://media.dcentertainment.com/sites/default/files/superman-150x180.jpg" onload="this.style.bottom = '' + (150 - this.offsetHeight) + 'px'" />
</div>

Answer №2

Try using height: 100%!

#container {
    width: 150px;
height: 150px;
overflow: hidden;
border: 1px solid;
position: relative;
}
#container img:hover { 
    height:100%;
}
<div id="container">
<img class="fl" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQiWGXo4U6CCvNItlDYFgEQz4d3T-YjLj13nqUZ-crpAr3qMPx-"/>
</div>

Answer №3

  1. To achieve a hover effect, utilize the transition property on an image.
  2. Select a fixed px height for the div containing the image to maintain consistency.
  3. Avoid using absolute positioning for the image unless necessary (e.g., when other elements are present inside the div).

Check out the following code snippet:

<div class="imgWrap">
  <img src="http://lorempixel.com/g/150/180" alt="" class="img1"> 
</div>

Below is the corresponding CSS code:

.imgWrap{
  width:150px;
  height:150px;
  overflow:hidden;
}
.img1{

  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}
.imgWrap:hover .img1{
  margin-top:-30px
}

Feel free to explore this concept further with a live demo available at this link.

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

Oops! Looks like there's an unexpected error with the module 'AppRoutingModule' that was declared in the 'AppModule'. Make sure to add a @Pipe/@Directive/@Component annotation

I am trying to create a ticket, but I encountered an error. I am currently stuck in this situation and receiving the following error message: Uncaught Error: Unexpected module 'AppRoutingModule' declared by the module 'AppModule'. Plea ...

determine the position of a row within a table using jQuery

I am working with a dynamically added table on my webpage. $("#myTable").on("click", "tr .eliminar.tooltip", function() { var myCol = $("#myTable").index(); //ok var $tr = $("#myTable").closest('tr'); // ok var myRow = $tr.index(); // wr ...

"Concealing sibling sections on the same level with JQuery - a helpful guide

As someone who primarily works on backend development, I am fairly new to JQuery. Currently, I have a specific table structure that looks like this: <tr> <td> <div class="div-package-service"><a style="cursor: pointer" id="service ...

Can JavaScript be utilized to dynamically adjust the size of all elements on the screen to a specified percentage of their initial height and width when a certain event occurs?

I'm fairly new to the world of JavaScript, but I have a basic understanding of it. I want to optimize my personal website for mobile devices. I've already taken care of screen orientation and element positioning, everything is centered nicely and ...

What could be causing the abundance of API calls from Yandex Metrica?

In my Nextjs SPA, there is an iframe widget that is rendered using React. Inside this widget's index.html file, I have inserted the Yandex Metrica script and set up a goal tag to track user clicks on the registration button. The goal tracking is wor ...

Mastering Meteor: Techniques for Manipulating Mongodb Data in Real Time Display

Within my Meteor application, I have accomplished the successful publication of data from the server and its subscription on the client side. Instead of directly displaying raw data on the client's screen, I am interested in performing some calculatio ...

Error in Typescript: Function declarations are not allowed in blocks while in strict mode

When attempting to run a script, I encountered the following error message: Function declarations are not permitted in blocks in strict mode during targeting of the 'ES3' or 'ES5' version. The modules are automatically in strict mode. ...

Could someone provide some insights on how the ( !! ) operator functions?

Angular 6 has arrived and while browsing through a quick tutorial on Medium, I stumbled upon this interesting piece of code. else if (!!this.day4Name && !this.day5Name && days[date] !== this.day4Name) { this.day5Name = days[date]; ...

Ways to determine if a link exists on a page using Jquery

One element on my website is a link: <a href="https://mywebsite.com/terms-conditions-mywebsite" target="_blank">Terms and conditions</a> I'm looking to use Jquery to verify if this particular link appears on the webpage. While I have exp ...

Whenever I select an item from one dropdown menu, it should automatically disappear from the other dropdown menu

I'm currently working on an HTML and PHP exercise that involves calculating distances between cities. My professor has requested the implementation of a select element in such a way that if "City A" is selected in one dropdown, it cannot be chosen aga ...

The Camera component in React Native is not currently supporting foreground service

Trying to capture images in a foreground service, such as taking pictures while the user is using another app. Everything works fine within the app, but when the app is closed with the foreground service active, the camera stops working and shows this erro ...

The scrolltop function is dysfunctional on CentOS operating systems

I'm currently working on implementing smooth scrolling functionality when a button is clicked. The feature works perfectly fine with a local Apache server and IE10+, but when the project is deployed on "CentOS", it doesn't work on the same browse ...

Whenever I create a new JavaScript application, the CSS files do not seem to reflect the most recent changes

My Next.js App is running smoothly on my client when I do npm run build and test it with node server js. However, the issue arises when I move the app to a production server. After executing npm run build on the server, everything seems to work fine except ...

reconfigure form credentials with JavaScript

I am currently working on a form that includes a textbox and a button for submitting data using ajax. <input type="password" id="password" /> <button id="addaccount" onclick="showload();">Add</button> When the user clicks on the button, ...

HTML Techniques: Flipping the Script - Writing Characters from Right to Left

In order to showcase the temperature in degrees Celsius, I have implemented a placement technique using absolute positioning. Consequently, the °C symbol will persist in its designated spot. To achieve the desired presentation, the text should be displaye ...

What is the best way to create a directive that wraps the div elements utilized in an ng-repeat loop?

When working on my application, I utilize this HTML snippet for an ng-repeat: <div class="gridBody"> <div ng-class="{clicked: row.current == true}" ng-click="home.rowClicked($index)" ng-dblclick="ctrl.rowDoub ...

Nodeca's js-yaml now allows appending '>-' to handle extended strings with ease

With the npm package js-yaml, I am attempting to work with a .yaml file. Although I can manipulate it successfully, I encounter an issue when trying to save a long string. Actual: abvs_adas: >- c2Rhc2Rhc2Rhc2Rhc2RwaW9qbGtkZ2hqbGtzZGhmZ2psaGFzamh ...

Exploring the dynamics of state manipulation in React

In managing a state, I have established a pricing system for coffee for employees when a radio button is selected. const [coffee, setCoffee] = useState(0); const [checkedCoffee, setCheckedCoffee] = useState(true); This is how the new state is being co ...

Customizing vertical padding in Bootstrap 4 Tables: Adjusting the spacing between rows

<div class="table-wrapper"> TABLE STUFF </div> I'm using Bootstrap to create a table with no borders, but I'm finding that the rows have too much vertical padding. How can I adjust the padding to create a more compact design? ...

When using the `mongoose find()` method, the returned _id may not match the one stored in

Just had a bizarre experience while working with MongoDB recently. It appears that when I make a query in a collection for a document, instead of returning the _id stored in the database, it generates a new _id for the queried document. For instance: In ...