I have an image and a <p>
inside a <div class = "man">
with display: flex
. When I try to resize the window with the dev tools, the margin-right
of the div colored with orange in the image is not respected, so the image seems stuck to the right side. The image for now has no padding/margin, but there is a margin applied to the div that contains both the <p>
and the <img>
; why is it not respected?
Screenshot of my issue w/ dev tools open
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div.man {
max-width: fit-content;
margin: 20px;
display: flex;
}
div.man p {
margin: 0px;
}
div.man img {
max-width: 450px;
height: auto;
}
@media (max-width: 655px) {
div.man {
flex-direction: column;
}
}
</style>
</head>
<body style="margin: 0px;">
<div style="width: fit-content;" class="man">
<img src="man2.jpg">
<p>Questo concept restaurant desidera donare ai propri membri un viaggio sensoriale e spirituale tramite le linee
del design, l'attenta scelta dei suoni, l'accurata selezione delle essenze, un'altra riflessione della
funzionalità e della comodità
</p>
</div>
</body>
</html>
This is a box model issue. The margin property does not work as many expect. When you apply a margin to an element the space is applied outside of the box model. This is why your image is shifted slightly past the viewport - the extra margin is pushing it out of the box model.
The width on the flex parent is set to fit-content but it also has a margin of 20px on all sides. This means that the flex parent box model will use the available space, but never more than max-content. In this case the max-content would be the width of the viewport, but since the flex parent has a margin of 20px on all sides the max-content is calculated in an unexpected way which makes it 20px wider than the viewport.
There are a few ways to address this. For the least amount of changes, I would recommend adjusting your CSS to reflect the following:
div.man {
max-width: fit-content;
padding: 20px;
gap: 20px;
display: flex;
}
Also make sure to close and reopen Chrome developer tools.