What is the best way to ensure an image is responsive in CSS and aligns perfectly in height with its neighboring text?

There is an image within the <img> tag and some text inside the <p> tag, both enclosed in a <div>.

Although the image is responsive and resizes proportionally when the browser window changes size, there is an issue where as the text wraps onto multiple lines below, the height of the image decreases in relation to the adjacent text. This affects the design of my site negatively. How can I ensure that the image maintains equal height with the neighboring text when the browser window is resized.

It's important to mention that when the browser window size is less than 768px, both the image and text block expand to 100% width and stack on top of each other.

To better understand the problem, please refer to the screenshots provided below. The first image shows the gap below the image - this is the issue that needs to be resolved. I want the image to stretch all the way down to the baseline of the last line of text while maintaining its aspect ratio.

Current Problem:

https://i.sstatic.net/tQPeK.png

Desired Result:

https://i.sstatic.net/yX2Px.png

EDIT

Please note that adding HTML width and height attributes to the <img> tag does not impact the image dimensions if CSS rules for image dimensions are specified.

In situations where content is generated from a WYSIWYG editor, it may not be feasible or practical to remove these HTML attributes manually. Especially if I am not the one creating the content.

* {
  -webkit-box-sizing:border-box;
  -moz-box-sizing:border-box;
  box-sizing:border-box;
  margin:0;
}

img {
  max-width:100%;
  height:auto;
}

.container {
  max-width:1200px;
  border:1px solid #eeeeee;
  margin:0 auto;
}

.col {
  width:100%;
  float:left;
  padding:15px;
}

.container {
  content:"";
  display:table;
  clear:both;
}

@media only screen and (min-width: 768px) {
  .left {
    width:25%;
  }

  .right {
    width:75%;
  }
}
<div class="container">
<div class="col left">
    <img src="images/nature.jpg" width="640" height="480" />
  </div>
<div class="col right">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec ligula ut tortor convallis ultricies sed vel leo. Nullam congue ligula sed lectus viverra rhoncus. Nullam tincidunt nibh sed ligula maximus faucibus. Nunc eu mauris purus. Vestibulum et nisl ut massa finibus laoreet in sit amet tortor. Suspendisse non leo quam. Ut consectetur dictum nibh vel vehicula. Vestibulum lobortis purus quam, id mattis purus sollicitudin volutpat. Maecenas ut libero in nisi egestas ornare nec ac lectus. Nullam urna nisi, rhoncus vitae viverra mattis, imperdiet nec velit. Aenean libero elit, luctus id maximus at, congue eget tortor. Nunc ultricies, augue eget facilisis luctus, nisl nibh aliquet libero, id ullamcorper ligula leo auctor ex.</p>
  </div>
</div>

Answer №1

Check out this concept using flexbox, width, and object-fit:

.container {
  max-width: 1200px;
  border: 1px solid #eeeeee;
  margin: 0 auto;
}

.left img {
  max-width: 100%;
}

@media only screen and (min-width: 768px) {
  .container {
    display: flex;
  }
  .left {
    position: relative;
    flex: 0 0 30%;
  }
  .left img {
    position: absolute;    /* take it of the flow, so it doesn't stretch the parent if    col right is shorter */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .right {
    flex: 0 0 75%;
  }
}
<div class="container">
  <div class="col left">
    <img src="https://picsum.photos/id/1041/640/480" width="640" height="480" />
  </div>
  <div class="col right">
    <h1>Please run in fullpage mode, then resized</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec ligula ut tortor convallis ultricies sed vel leo. Nullam congue ligula sed lectus viverra rhoncus. Nullam tincidunt nibh sed ligula maximus faucibus. Nunc eu mauris purus. Vestibulum
      et nisl ut massa finibus laoreet in sit amet tortor. Suspendisse non leo quam. Ut consectetur dictum nibh vel vehicula. Vestibulum lobortis purus quam, id mattis purus sollicitudin volutpat. Maecenas ut libero in nisi egestas ornare nec ac lectus.
      Nullam urna nisi, rhoncus vitae viverra mattis, imperdiet nec velit. Aenean libero elit, luctus id maximus at, congue eget tortor. Nunc ultricies, augue eget facilisis luctus, nisl nibh aliquet libero, id ullamcorper ligula leo auctor ex.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec ligula ut tortor convallis ultricies sed vel leo. Nullam congue ligula sed lectus viverra rhoncus. Nullam tincidunt nibh sed ligula maximus faucibus. Nunc eu mauris purus. Vestibulum
      et nisl ut massa finibus laoreet in sit amet tortor. Suspendisse non leo quam. Ut consectetur dictum nibh vel vehicula. Vestibulum lobortis purus quam, id mattis purus sollicitudin volutpat.</p>
  </div>
</div>--

Here's the table version with display:table:

.container {
  max-width: 1200px;
  border: 1px solid #eeeeee;
  margin: 0 auto;
}

.left img {
  max-width: 100%;
}

@media only screen and (min-width: 768px) {
  .container {
    display: table;
    width: 100%;
    table-)layout: fixed;
  }
  .left {
    display: table-cell;
    width: 25%;
    position: relative;
    flex: 0 0 30%;
  }
  .left img {
    position: absolute;
    /* take it of the flow, so it doesn't stretch the parent if    col right is shorter */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  .right {
    padding-left: 1em;
  }
}
<div class="container">
  <div class="col left">
    <img src="https://picsum.photos/id/1041/640/480" width="640" height="480" />
  </div>
  <div class="col right">
    <h1>PLZ, run in fullpage mode , then resized</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec ligula ut tortor convallis ultricies sed vel leo. Nullam congue ligula sed lectus viverra rhoncus. Nullam tincidunt nibh sed ligula maximus faucibus. Nunc eu mauris purus. Vestibulum
      et nisl ut massa finibus laoreet in sit amet tortor. Suspendisse non leo quam. Ut consectetur dictum nibh vel vehicula. Vestibulum lobortis purus quam, id mattis purus sollicitudin volutpat. Maecenas ut libero in nisi egestas ornare nec ac lectus.
      Nullam urna nisi, rhoncus vitae viverra mattis, imperdiet nec velit. Aenean libero elit, luctus id maximus at, congue eget tortor. Nunc ultricies, augue eget facilisis luctus, nisl nibh aliquet libero, id ullamcorper ligula leo auctor ex.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec ligula ut tortor convallis ultricies sed vel leo. Nullam congue ligula sed lectus viverra rhoncus. Nullam tincidunt nibh sed ligula maximus faucibus. Nunc eu mauris purus. Vestibulum
      et nisl ut massa finibus laoreet in sit amet tortor. Suspendisse non leo quam. Ut consectetur dictum nibh vel vehicula. Vestibulum lobortis purus quam, id mattis purus sollicitudin volutpat.</p>
  </div>
</div>--

Answer №2

To ensure the code functions properly, delete the height and width attributes from the HTML file.

For the image tag's CSS attribute height, set it to 100% instead of auto.

Replace:

img {
  max-width: 100%;
  height: auto
}

with:

img {
  max-width: 100%;
  height: 100%;
}

This modification should resolve any issues.

Answer №3

After reviewing the issue, I have modified the HTML to address it. Below is a revised example, and if it does not meet your requirements, please inform me:

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
}

img {
  max-width: 100%;
  height: auto
}

.container {
  max-width: 1200px;
  border: 1px solid #eeeeee;
  margin: 0 auto;
}

.row {
  display: flex;
}

.col {
  width: 100%;
  float: left;
  padding: 15px;
}

.container {
  content: "";
  display: table;
  clear: both;
}

.h-100 {
  height: 100%;
}

@media only screen and (min-width: 768px) {
  .left {
    width: 25%;
  }
  .right {
    width: 75%;
  }
}
<div class="container">
  <div class="row">
    <div class="inner-wrapper col left">
      <div class="h-100 row">
        <img src="https://picsum.photos/1200" />
      </div>
    </div>
    <div class="inner-wrapper col right">
      <div class="row">
        <p class="">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque nec ligula ut tortor convallis ultricies sed vel leo...ex.</p>
      </div>
    </div>
  </div>
</div>

If this solution does not work for you, please reach out for further assistance.

Answer №4

Tip #1 : Set the height to 100%

Tip #2 : Apply display: flex; to the parent container of the left and right columns

For example :

<div class="container" style="display:flex;">
  <div class="left col">
    <img src="myimage" style="height:100%" />
  </div>
  <div class="right col">...my content..</div>
</div>

Remember to set the height of <img> to 100% if it is within another div

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

Adjusting the width of a nested iframe within two div containers

I am trying to dynamically change the width of a structure using JavaScript. Here is the current setup: <div id="HTMLGroupBox742928" class="HTMLGroupBox" style="width:1366px"> <div style="width:800px;"> <iframe id="notReliable_C ...

Can Phonegap be utilized to port a PlayN game to iOS?

PlayN seems like a fantastic tool for creating Html5 games. I'm curious to know if there are any plans to ensure that the html/javascript output is compatible with Phonegap, ultimately allowing for the creation of an iOS executable? ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Utilizing HTML and JavaScript to dynamically switch stylesheets based on the width of

When it comes to using stylesheets for mobile and non-mobile devices, there is a need for different approaches. The idea of comparing browser height and width in JavaScript seems like a good one, but the implementation may not always work as expected. ...

Retrieving specific value from a Parent Controller in AngularJS using UI Router

I have a request to display the value stored in $scope.resAVal on my index.html page. This value is accessible within the RootCtrl. index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <!-- any required JavaScript librarie ...

How can I immediately disable a button upon clicking "cancel" on a modal that contains TextFields in React Version 18?

New to React development. Looking for a way to reset a button to its initial disabled state when canceling out of a modal. The scenario is that upon clicking a button, a dialog will appear with an "ADJUST" button that is initially disabled until text is ...

Check to see if the menu item exceeds the allotted space, and if so, display the mobile menu

Currently, I am in the process of creating a unique responsive menu for my website that I think will need some JavaScript implementation. My skills with JavaScript are not very strong, so I am looking for guidance, code examples, or resources that can assi ...

"Click here to access the downloadable content obtained through web scraping

I am looking to automate a task using Python where I need to get a PDF file from a website with fileid 8426 and date 03312021. Visit this link: Click on the "Download PDF" button Save the downloaded file to a directory After exploring, I came across a P ...

"What is the best way to transform tab navigation into a dropdown menu with the help

I have a collection of tabs currently on display. I am looking to transform them into a dropdown menu when the screen size changes, making them more responsive. Each set of tabs corresponds to different content. Despite trying various solutions found on s ...

Customizing the appearance of a local image with inline CSS using the style attribute and background-image:url

I'm having trouble loading the image Hormiga.jpg as a background for my slideshow using inline style. The url attribute doesn't seem to be applied correctly. Here is the original code where an image is loaded successfully: <div class="pa ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Choose an item from my unordered list to automatically set the value of a form input

Hello, I am looking for a way to make a long Unordered list always visible on my website. I want users to be able to click on one of the List Items and have that item appear as the value in my Form type=text. I believe using Jquery would be the best way ...

What is the best method to ensure that none of the select option values are left empty?

I have a total of 5 select option drop down menus currently, but this number may increase in the future depending on requirements. The issue I'm facing is that when I select the last element, it returns true even though the other elements are empty. I ...

Can an ID and a "<?php echo ''.$variable.'' ?>" be included in the same input or video tag?

I have a task where I need to insert various Ids into a single video input tag. Specifically, I need to include the player and its row ids from PHP in this format: <video preload controls playsinline id="player[<?php echo ''.$row5['id ...

What is the maximum allowable size for scripts with the type text/json?

I have been attempting to load a JSON string within a script tag with the type text/json, which will be extracted in JavaScript using the script tag Id and converted into a JavaScript Object. In certain scenarios, when dealing with very large data sizes, ...

Is there a way to mimic this type of scrolling effect?

Upon visiting this website, it is evident that the entire interface has been constructed with React. The scrolling experience on this site is exceptionally smooth, although it may feel slightly more substantial than a typical scroll. After researching onli ...

Enhance your CSS link in Yii framework 2.0 by incorporating media printing capabilities

While working on Yii framework 2.0, I typically include a CSS file by adding the following code snippet to assets/AppAsset.php: public $css = [ 'css/style.css', ]; Upon inspecting the element in the web browser, I notice the following code ...

Tweaking react-lottie and SVG dimensions with CSS media queries: A step-by-step guide

I am currently working on a React project that involves displaying Lottie-react animations and SVG's. My main concern is making sure that these illustrations are responsive on my website. The components are stored in a .js file, which I import into m ...

Creating a chic look for your conditional statement: If Else Styling

While it may not be possible to directly style PHP code, you can definitely style the HTML output that PHP generates. I'm curious if there's a way for me to apply styles to the output of an IF ELSE statement. if ($result != false) { print "Y ...

Display the widget beyond the boundaries of the sidebar

Currently, I am using my own custom theme called Total. I want to display the Sidebar Login plugin's widget in the header section of my website. I attempted to do this with the following code: <div class="login"><?php the_widget('sideba ...