Home > other >  how to make responsive an <img> contained in a parent with display:flex?
how to make responsive an <img> contained in a parent with display:flex?

Time:04-27

Basically I have a layout where I have 3 elements inside a parent with display:flex.

<div >
 <div >Title</div>
 <div ><img src="https://cdn.colombia.com/images/v2/colombia-info/informacion/informacion-800.jpg" /></div>
 <div ><button>Button</button></div>
</div>

I should not have scroll in any direction. The idea is that the middle div:

<div ><img src="https://cdn.colombia.com/images/v2/colombia-info/informacion/informacion-800.jpg" /></div>

takes the remaining space between .titleContainer and .buttonContainer, that's why it has the flex-grow:1 property.

The problem is that if I put an <img/> there is a problem of vertical and horizontal scroll,

enter image description here

this does not happen if I put any other element.

How can I make that the image does not cause scrolling problems and adapts to the available space? I need to know how to fix this problem using an <img/>.

Thank you very much

html,body{
  padding:0px;
  margin:0px;
  height:100%;
}

*{
 box-sizing: border-box;
}

img{
 margin:0px;
 padding:0px;
}

.flex{
 display:flex;
 border:1px solid red;
 flex-direction:column;
 height:100vh;
}

.titleContainer{
 border:1px solid blue;
}

.buttonContainer{
 border:1px solid green;
}

.imageContainer{
  flex-grow:1;
}
<div >
  <div >Title</div>
  <div ><img src="https://cdn.colombia.com/images/v2/colombia-info/informacion/informacion-800.jpg" /></div>
  <div ><button>Button</button></div>

</div>

CodePudding user response:

You can use media Queries to make the image smaller in size. in the css part add the following

@media all and (max-width: 1024px) and (min-width: 768px){ 
  img{
   width:200px; //or something like this. Change the size of the image. 
    }
}

There are more details on media queries on here - https://css-tricks.com/css-media-queries/

CodePudding user response:

test this out

.flex{
width:100%;
overflow:hidden;
align-content: center;
justify-content: flex-start;
}

CodePudding user response:

You always have to define the width and height for the photo sometimes you dont need to define height you just have to set width:100%; it will be responsive

html,body{ 
padding:0px; margin:0px; height:100%; 
} 
*{ 
box-sizing: border-box; 
} 
img{ 
margin:0px; padding:0px; width:100% !important; 
} 
.flex{ 
display:flex; border:1px solid red; flex-direction:column; height:100vh; 
} 
.titleContainer{ 
border:1px solid blue; 
} 
.buttonContainer{
border:1px solid green; 
} 
.imageContainer{ 
flex-grow:1; 
}
<div > 
<div >Title</div> 
<div ><img src="https://cdn.colombia.com/images/v2/colombia-info/informacion/informacion-800.jpg" /></div>
<div ><button>Button</button></div> 
</div>

  •  Tags:  
  • css
  • Related