How to solve the small gap under the img tag

Many beginners have encountered a problem when writing a page. When we wrap the img directly with a div, a 3px spacing will appear below the img, as shown in the figure

Code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>
		<style type="text/css">
			.box {
				border: 2px solid red;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<img src="img/4.png">
		</div>
	</body>
</html>

What is the reason?

Img is a label element similar to text. At the end, a blank character (anonymous text) will be added at the end, resulting in an extra 3px spacing below. In fact, we add a span to the right of the img to wrap the text. Will be more obvious

There are five ways to solve the above problems

the first method:

Set the same height to the div as the img;
disadvantage: this method is not flexible enough, once the img size changes, we have to reset the height of the div

The second method:

Img to set vertical-align to other baseline than a value used

The third method:

Add display: block to the img;
this method is more commonly used by us, but it should be noted that once the img is set as a block, text-align: center; it will no longer take effect. The horizontal centering of the image should use margin: auto;

The fourth method:

Img set to float
set will float out of the document flow img
drawback: the parent element height will not be automatically stretched img

The fifth method:

Set to div font-size:0;
Disadvantages: This method will make the text disappear div

Choose the right method according to the actual situation; make my goddess more perfect!

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/108600979