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

Transformation of looks post a refresh

Initially, the CSS and appearance of the page look fine when I first open it (after clearing the cache). However, upon refreshing the page, a part of it changes (specifically, the padding direction of a div). This change occurs consistently with each refre ...

ExpressJS refuses to wait for my promise to be fulfilled

I'm in the process of creating a search-page on my server. Whenever the endpoint is accessed and the user waits for the search function to deliver the results and display them on the page, Express somehow redirects to the 404 handler instead. An error ...

Is it possible for a submission of a form to modify the content length header, resulting in the request failing?

Issue Description: After binding a submit event to an AJAX post request in order to send a predetermined key-value pair to a PHP script, the expected message indicating successful communication is not received. Despite the fact that the submit event trig ...

Error in PHP script when making an AJAX call

First of all, I want to thank you all for your help. The script is creating a table but sending empty information. I have tried to modify it like this: However, when I call the script, it gives me an error: So, I have edited the script code to clean it ...

Bootstrap Table with Numerous Rows and Columns

I am striving to create a table layout similar to the one shown in the image using bootstrap 5. https://i.sstatic.net/lEnYX.png My attempt so far looks like this <table class="table table-bordered"> <thead> <tr> ...

Struggling to figure out how to make Bootstrap toast close or autohide properly

Looking to integrate Bootstrap 5 toasts into my ASP.NET web application, I have the code below. HTML <div class="row"> <div class="toast" id="companyUpdOK" name="compa ...

What is causing the action button in my MUI snackbar to occupy an additional line?

I'm currently learning how to use MUI and I'm struggling with a specific issue. The close button in my code is appearing on a separate line, but I want it to be on the same line as the word "again". I've tried experimenting with absolute pos ...

In order to activate the input switch in Next.Js, it is necessary to initiate a

Currently, I am working on implementing an on-off switch in Next.Js. To seek assistance, I referred to this helpful video tutorial: https://www.youtube.com/watch?v=1W3mAtAT7os&t=740s However, a recurring issue I face is that whenever the page reloads, ...

HTML Multi-Column List Box

Can a List Box be created with List Items displayed in Multiple Columns? I know there are other options available, but I'm curious if this is achievable using the <select> tag ...

Is it possible to run an existing NextJS app with API routes on a mobile platform using either Capacitor or Expo?

I have an established NextJS application that heavily relies on Next's API routes. My goal is to transition the current codebase to function in a mobile environment. I've experimented with Capacitor and attempted to export it as a static site, bu ...

Avoid obtaining cookies within the TRPC environment

Recently, I've been setting up TRPC with Next.js and attempting to implement server-side rendering where I fetch user data before the page loads using the trpc.useQuery hook. However, I'm facing an issue where I cannot access the JWT token cookie ...

How can one implement a redirect in a React hook using useEffect?

I have a question regarding redirecting a non-logged-in user to the login page in my application. I am using some conditions within a useEffect function inside my routes file, but for some reason, the redirect doesn't seem to be working properly. I&ap ...

Is there a way to dynamically set a database path in Express.js depending on the user's login status?

I have a backend service that serves as the primary entry point for my web application, where I want to dynamically allocate a database path based on user login. While I understand that this solution may not be scalable in the long run, I plan to use it fo ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

The pre-line white-space property is not functioning as anticipated in my CSS code

content: string; this.content = "There was an issue processing your request. Please try using the browser back button."; .content{ white-space: pre-line; } <div class="card-body text-center"> <span class="content"> {{ content }} </span& ...

Rails not receiving JSON data

I am attempting a straightforward ajax call in Rails 4, but encountering issues with retrieving the json response. Below is the script I'm working with: $(document).on "submit", "form[name=upvote-form]", -> form = $(this) $.post "/vote", $(th ...

Postponing the findings of a database for a quarter of an hour

Hey there, I'm a new coder and like to dabble in a bit of everything, so go easy on me! So, here's the deal: data from a poker tournament is constantly being updated in a database, but we're delaying the video feed by 20-25 minutes to preve ...

Fade in and out effects created using styled-components in React

Looking for some help with creating a React component that can handle both fading in and fading out. Currently, when passing the out prop to the component in the code snippet below, it is hidden before animating out. My goal is to have it fade in by defaul ...

determining the sorting behavior of columns in Datatables

While working on my table, I referred to a Datatbles tutorial that covers sorting the third column as a percentage value. // Setting up column search - adding a text input to each footer cell $('#p_table-id tfoot th').each(function ...

Struggles with implementing CSS Grid's dynamic column heights and expanding rows

Linked partially to Removing empty space in CSS Grid, with specific adjustments I am aiming for. Essentially, I want my rows and columns to expand and contract based on the content present. In this CodePen example, you can observe that the content of the ...