Increasing the maximum width of an image in CSS is necessary to see the max-height take effect

Within my HTML structure:

<Col md="6">
  <div className="hero-section">
    <div className={`flipper ${isFlipping ? "isFlipping" : ""}`}>
      <div className="front">
        <div className="hero-section-content">
          <h2> Full Stack Web Developer </h2>
          <div className="hero-section-content-intro">
            Have a look at my portfolio and job history.
          </div>
        </div>
        <img
          alt="programming welcome picture"
          className="image"
          src="/images/original.png"
        />
        <div className="shadow-custom">
          <div className="shadow-inner"> </div>
        </div>
      </div>
</Col>

My CSS styling for the image is as follows:

.hero-section {
  h2 {
    color: black;
    font-weight: bold;
    margin-bottom: 10px;
  }

  perspective: 10rem;
  color: black;
  font-weight: bold;
  width: 40rem;
  position: relative;

  &-content {
    position: absolute;
    bottom: 20px;
    width: 360px;
    left: 6%;
    z-index: 1;

    &-intro {
      font-size: 17px;
    }
  }
}

 .image {
  max-width: 100%;
  max-height: 50%;
  position: relative;
  background-position: center;
}

After testing different configurations for the image CSS, including:

.image {
  max-width: 100%;
  // background-size: cover;
  // max-width: 100%;
  max-height: 100%;
  position: relative;
  background-position: center;
}

I noticed that changing the width affects the height, but my goal was to specifically adjust the height alone. This led me to try the following settings:

.image {
  max-height: auto;
  max-width: 100%;
  background-position: center;
  background-size: cover;
}

Despite these efforts, I faced challenges where the text was appearing outside the boundaries of the image. It seems that even with `max-width: 100%`, the image was not expanding as wide as expected.

This dilemma can be visualized through the following link: [https://i.sstatic.net/6fqsc.png](https://i.sstatic.net/6fqsc.png).

Answer №1

[Edit]: Oops, it seems I have the privilege of being the only one with a flawlessly working stackblitz here on earth. Just in case, here's the code:

<div className="content">
    <h2>FullStack developerdfghbdfg</h2>
    <p>Were you searching for something like this?</p>
</div>

And now for the CSS section :

.content {
  padding: 15px;
  padding-top: 200px;
  max-width: 200px;
  background-image: url('https://picsum.photos/200/300'); /* You'll need an HD image for this */
  background-size: cover; /* This will stretch your image */
  color: red; /* Quite garish, isn't it? */
}

Is this what you were looking for? Check out the Stackblitz example

If not, could you describe the shape of your image? Is it a long vertical image in shades of blue, or does it feature characters, screens, and books against a solid blue background within your container?

Answer №2

What causes the text to be positioned outside of the image?

In short: The image is narrower than 40rem.

Here's a summarized version:

When the max-width is set to 100%, the image can take up its full intrinsic width, but with the height set to auto, the image width is determined by the intrinsic height, resulting in a fractional width less than 100%.

Why does the image appear wider and taller compared to your initial scenario?

.image {
  // Allows the image to fill 100% of its width
  max-width: 100%;
  // Allows the image to fill 100% of its height
  max-height: 100%;
  ...
}

The image is using its intrinsic width/height values since the <img> element is considered a replaced element type and the object-fit CSS property is not specified.


Solution 1

Set div.hero-section to a fixed width and height, like this

.hero-section {
  // e.g., height/width can be any desired value
  height: 20rem;
  width: 40rem;
  ...
}

Then, add the object-fit: cover property in the .image class

.image {
  ...
  object-fit: cover
}


Solution 2

Utilize the image as a background image. Remove the .img class and the image markup entirely from HTML. Adjust the .hero-section CSS as follows


.hero-section {
  ...
  width: 40rem;
  height: 20rem;
  background-size: cover;
  background-position: center;
  background-image: url("/images/original.png");
  ...

}

A preview of the code can be found in my codesandbox link below

https://codesandbox.io/s/async-mountain-0qkgc?fontsize=14&hidenavigation=1&theme=dark

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

Is there a way to trigger both the link and the div element simultaneously?

Is there a way to make both the button and the link light up simultaneously when hovering over the div element, instead of just the button lighting up first? <div id="b1"; class = b> <a href="test.html">BUY</a> < ...

Encasing common functions within (function($){ }(jQuery) can help to modularize and prevent

As I was creating a global JavaScript function and made some errors along the way, I finally got it to work after doing some research. However, while searching, I came across an example using (function($){ code here }(jQuery); My question is, what exact ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...

React-built NPM website fails to compile

After successfully running my website created with ReactJS on my local machine, I encountered an error when trying to build it using npm run build. The error message received was: > react-snap � pageerror at /personal-site/: SyntaxError: Unexpected ...

Is it possible to apply a click effect to a specific child element of a parent using jQuery?

Struggling to figure out how to modify this jQuery code so that only the parent of the clicked button displays its child. Currently, all children are displayed when any button is clicked, not just the one within the targeted parent. I attempted using $(t ...

What sets apart jQuery.ajax's dataType="json" from using JSON.parse() for parsing JSON data?

What is the difference between using dataType='json' and parsing response with JSON.parse(response) in jQuery Ajax? $.ajax({ url: path, type: 'POST', dataType: 'json', data: { block ...

Looking for the properties of the ServerResponse object in node.js - where can I locate them?

Currently, I've been diving into the book Node.js In Action. Chapter 9 introduces a message module with a function that has left me puzzled about the 'this' object when calling res.message. To gain clarity, I decided to print out the name of ...

Possible rewrite: "Tips for extracting columns and rows from object data in React using '@material-ui/data-grid'"

I am currently working on retrieving data from a mockapi and displaying it on my data grid. The data grid requires specific rows and columns to be defined. While I have manually set these up for practice, I now aim to fetch object data using axios and th ...

Saving information in node.js

My latest project involves creating an address book app using HTML, CSS, and JavaScript. The company provided me with a zip file containing the necessary resources to implement the app using node.js. However, my knowledge of node.js is limited and I have ...

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

Issue with Bootstrap modal not closing

I've encountered an issue with a bootstrap modal popup. When I try to close the popup, it doesn't behave as expected. Instead of just hiding the popup and removing the backdrop, it hides the popup but adds another backdrop, making the screen almo ...

What is the correct way to use forwardRef in a dynamic import in Next.js?

I've been trying to incorporate the forwardRef in my code, but I'm facing some difficulties. Can anyone help me out with this? I'm encountering the following errors: Property 'forwardedRef' does not exist on type '{}'. ...

Turn off the custom CSS section in the WordPress Customizer for WordPress themes

Looking for assistance in locking or disabling the Appearance -> Customizer -> Additional CSS area on Wp-admin. I have referred to this codex: https://codex.wordpress.org/Theme_Customization_API. However, I couldn't find any hook or function to disab ...

Is there a way to customize grid system breakpoints?

Seeking assistance with material-ui Grid system. My full page is responsive but I'm struggling to make the grid components overflowX with a fixed header, resulting in only the Grid container having a horizontal scrollbar. Despite trying various soluti ...

Add space between the first and second rows in the grid gallery display

.gallery{ display: grid; grid-template-columns: repeat( auto-fit, minmax(250px, 1fr) ); grid-template-rows: repeat( auto-fit, minmax(250px, 1fr) ); } view grid image here Could you assist me with identifying the spacing issue between the first and second ...

Using next-intl to translate zod error messages provides a straightforward solution for localization

I am interested in finding a solution for translating Zod error messages while utilizing the next-intl package. I am considering exploring options other than Zod-i18n or i18next. The decision to use next-intl over i18next is based on the compatibility wit ...

Instructions on designing a three-column layout for six separate div elements

i am having trouble organizing 6 div elements into 3 columns per row. Currently, I have them arranged in two rows, but the issue arises when a column's h2 element is long and it pushes down the column below, creating a large space in the second row. A ...

Guide on setting default attributes for all properties of an object at once

Currently, I'm in the process of developing an AngularJS service provider (function) that achieves the following objectives: Gathers data from multiple tables within an SQLite database Delivers the resulting object to various controller functions S ...

The table does not move up or down when using the mousewheel over the rows, but only when

I'm encountering an issue with a table inside a div that has overflow-y: scroll applied to it. While the scrollbar appears when there is content overflow, I am unable to scroll using the scrollwheel. It only works when the cursor is directly on top o ...

Display a 404 error page when the CMS Strapi does not contain a valid slug

Working with Strapi CMS and Next.js to display pages from the CMS, I need to change the status code to 404 in the browser network window. If a user lands on an unknown page where data is not found in the CMS, I want to redirect them to an error page and p ...