【问题标题】:make div the size of its contents [duplicate]使 div 其内容的大小[重复]
【发布时间】:2016-03-09 20:55:30
【问题描述】:

我正在尝试将 div 设置为其内容的大小,但我正在处理一条幽灵线。有人可以看看吗?

        * {
            margin: 0;
            padding: 0;
        }

        div#holder {
            background-color: blue;
            display: inline-block;
        }

        canvas {
            cursor: pointer;
            background-color: gray;
        }


    <div id="holder">
        <canvas id="canvas" width="300" height="300"></canvas>
    </div>

https://jsfiddle.net/xjmz6n68/

【问题讨论】:

    标签: html css


    【解决方案1】:

    这个小间隙是因为容器是一个内联元素,并且为字体中的下行元素(例如 j、g、y)保留了空间。通过在画布规则中添加 vertical-align:top 可以轻松删除它:

    canvas {
        cursor: pointer;
        background-color: gray;
        vertical-align: top;
    }
    

    jsFiddle example

    或在 div 上将 font-size 设置为零:

    jsFiddle example

    或浮动画布:

    jsFiddle example

    【讨论】:

      【解决方案2】:

      我已经找到了三个选项:

      display:block; 添加到canvas

      vertical-align:top; 添加到canvas

      display:inline-flex; 设置为您的div#holder

      【讨论】:

        【解决方案3】:

        给你的#holder CSS line-height: 0;

        由于您使用的是inline,因此会应用类似文本的行高。

        https://jsfiddle.net/svArtist/cm4r6k7p/

        【讨论】:

          【解决方案4】:

          默认情况下,画布是内联渲染的,就像字母一样,因此您可以使用以下解决方案:

          • display:blockcanvas
          • vertical-align: bottom; 到画布
          • float: left; 到画布
          • line-height: 0;div#holder

          .

          Jsfiddle

          【讨论】:

            【解决方案5】:
                canvas {
                        cursor: pointer;
                        background-color: gray;
                vertical-align: top;
                    }
            

            只需添加垂直对齐:顶部;画布并修复它。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-09-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-01-06
              • 2016-09-20
              相关资源
              最近更新 更多