Empty elements do not take up position processing

1. Problem scenario:

If you set the CSS of an element to margin-right: 10px, even if the content of this element is empty, then this 10px still exists, the effect is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span {
      
      
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <span>你好</span><span></span><span>helloWord</span>
</body>
</html>

The rendering effect is as follows:
insert image description here

2. Solution:

Use the pseudo-element: empty, if the element is empty, set the display to none.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span {
      
      
            margin-right: 10px;
        }
        span:empty {
      
      
            display: none;
        }
    </style>
</head>
<body>
    <span>你好</span><span></span><span>helloWord</span>
</body>
</html>

The rendering effect is as follows:
insert image description here


Reference: https://developer.mozilla.org/zh-CN/docs/Web/CSS/:empty
insert image description here

Guess you like

Origin blog.csdn.net/yexudengzhidao/article/details/131614764