Text within circle div. Div size adjusted to content

前端 未结 5 1132
庸人自扰
庸人自扰 2020-12-19 04:52

I want to create a circle div with text in (not only one line). This is the kind behavior I want:

\"http://i.img

5条回答
  •  既然无缘
    2020-12-19 05:38

    So here is the clean Script way.

    HTML:

    Your text

    CSS:

    *
    {
        margin: 0;
        padding: 0;
    }
    div
    {
        display: inline-block;
        border: 1px solid black;
        border-radius: 50%;
        text-align: center;
    }
        div:before
        {
            content: '';
            display: inline-block;
            height:100%;
            vertical-align: middle;
        }
    
    span
    {
        vertical-align: middle;
        display: inline-block;
    }
    

    JQuery:

    var width = Math.sqrt($("span").width() * $("span").height());
    var sqrt2 = Math.sqrt(2);
    $("span").height(width);
    $("span").width(width);
    $("div").width(sqrt2 * width);
    $("div").height(sqrt2 * width);
    

    because of spaces between the word, and how they break.. this solution may bug on small texts.

    same HTML & CSS, minor changes in Script

    Here's a better solution (works better even with small texts)

    JQuery:

    var div = $("div");
    var span = $("span");
    
    span.width(Math.sqrt(span.width() * span.height()));
    span.width(Math.sqrt(span.width() * span.height()));
    div.width(Math.sqrt(2) * span.width());
    div.height(div.width());
    

    the reason that I repeat that line

    span.width(Math.sqrt(span.width() * span.height()));
    

    its because the more I use it, the better I scale of the span around the text. (causing the circle to be tighter around the text)

提交回复
热议问题