I want to create a circle div with text in (not only one line). This is the kind behavior I want:
That I guess I can achieve with a
text-align: center;
vertical-align: middle;
But what if I don't know the height and width?
I want the circle to expand (min-size 100px) if the text is filling it up.
You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
Using width, max-width and margin: auto; Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins: This <div> element has a width of 500px, and margin set to auto.
So here is the clean Script way.
HTML:
<div><span>Your text</span></div>
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.
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)
Hope this helps you in any way, but be aware that it does not guarantee that all the content will be inside the circle!
I would create a div and a span to the content:
And then I would apply a CSS to border the div with a radius that would make it like a circle. Vertical alignmento of the span should place it in the middle.
<div>
<span>Content goes here</span>
</div>
And the CSS:
div{
border-style:solid;
border-color: black;
width: 300px;
height:300px;
text-align: center;
border-radius: 300px;
vertical-align:middle;
display:table;
padding: 5px;
}
span{
display:table-cell;
vertical-align:middle;
}
You may test it here: http://jsfiddle.net/S3cNW/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With