0

I have the following HTML

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title>
</title>
</head>
<body>
    <div>
        <img src="0.jpg" width="50%">
        <img src="1.jpg" width="50%">
    </div>
</body>
</html>

I expect the 2 images stay at same row. But they don't

enter image description here

I have to tweak the code to

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title>
</title>
</head>
<body>
    <div>
        <img src="0.jpg" width="49%">
        <img src="1.jpg" width="50%">
    </div>
</body>
</html>

enter image description here

I have tested Chrome/ Edge/ Firebox they both yield the same outcome.

May I know how I can fix such? Thanks.

Cheok Yan Cheng
  • 48,324
  • 124
  • 436
  • 828
  • Most likely there is additional padding or margin coming from one of the other elements. You can [read up here about box-sizing](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing). – crazymatt Nov 08 '21 at 20:25
  • I think this has something to do with the fact that images are inline-block by default. When you make the parent a display flex (so images are flex-items), It works perfectly fine. – Lucas David Ferrero Nov 08 '21 at 20:25

1 Answers1

1

Cause of the problem

The reason is that your browser treats your img tags as inline-block elements, meaning it also renders any whitespace between images as a single space character. Since 2x50% equals 100%, this leaves no room for the space.

How to fix

  1. Remove all whitespace:
<div><img src="0.jpg" width="50%"><img src="1.jpg" width="50%"></div>
  1. Eliminate whitespace effectively by setting font-size: 0; on the parent div:
<div style="font-size: 0">
  <img src="0.jpg" width="50%">
  <img src="1.jpg" width="50%">
</div>
  1. Use a more modern layout method like CSS grid (with this one, you omit assigning width to the images themselves):
<div style="display: grid; grid-template-columns: repeat(2, minmax(0,1fr))">
  <img src="0.jpg">
  <img src="1.jpg">
</div>
connexo
  • 49,059
  • 13
  • 74
  • 108
  • 1
    I am pretty sure you know that this question is the 2nd most frequent question in Stack Overflow – Temani Afif Nov 08 '21 at 20:32
  • and technically images are just `inline`-elements. They are just threaten by most browser like `inline-block` – tacoshy Nov 08 '21 at 20:37