Ответ 1
.circle {
width: 500px;
height: 500px;
border-radius: 50%;
font-size: 50px;
color: #fff;
line-height: 500px;
text-align: center;
background: #000
}
<div class="circle">Hello I am A Circle</div>
Я нашел этот пример в stackoverflow:
Рисовать круг, используя только css
Это здорово. Но я хотел бы знать, как изменить этот пример, чтобы включить текст в середине круга?
Я также нашел это: Вертикально и горизонтально центрируя текст по кругу в CSS (например, значок уведомлений iphone)
но по какой-то причине он не работает для меня. Когда я создаю следующий тестовый код:
<div class="badge">1</div>
вместо круга, я получаю овальную форму. Я пытаюсь поиграть с кодом, чтобы увидеть, как я могу заставить его работать.
.circle {
width: 500px;
height: 500px;
border-radius: 50%;
font-size: 50px;
color: #fff;
line-height: 500px;
text-align: center;
background: #000
}
<div class="circle">Hello I am A Circle</div>
Если ваш контент будет обернут и будет иметь неизвестную высоту, это ваш лучший выбор:
http://cssdeck.com/labs/aplvrmue
.badge {
height: 100px;
width: 100px;
display: table-cell;
text-align: center;
vertical-align: middle;
border-radius: 50%; /* may require vendor prefixes */
background: yellow;
}
.badge {
height: 100px;
width: 100px;
display: table-cell;
text-align: center;
vertical-align: middle;
border-radius: 50%;
background: yellow;
}
<div class="badge">1</div>
Вы можете использовать css3 flexbox
.
HTML:
<div class="circle-with-text">
Here is some text in circle
</div>
CSS:
.circle-with-text {
justify-content: center;
align-items: center;
border-radius: 100%;
text-align: center;
display: flex;
}
Это позволит вам располагать вертикально и горизонтально выровненные по одной строке и многострочный текст.
body {
margin: 0;
}
.circles {
display: flex;
}
.circle-with-text {
background: linear-gradient(orange, red);
justify-content: center;
align-items: center;
border-radius: 100%;
text-align: center;
margin: 5px 20px;
font-size: 15px;
padding: 15px;
display: flex;
height: 180px;
width: 180px;
color: #fff;
}
.multi-line-text {
font-size: 20px;
}
<div class="circles">
<div class="circle-with-text">
Here is some text in circle
</div>
<div class="circle-with-text multi-line-text">
Here is some multi-line text in circle
</div>
</div>
Я думаю, вы хотите написать текст в овале или круге? почему не этот?
<span style="border-radius:50%; border:solid black 1px;padding:5px">Hello</span>
Для веб-дизайна, который мне недавно был предоставлен, мне пришлось решить центрированное и неизвестное количество текста в проблеме с фиксированным кругом, и я подумал, что поделился бы решением для других людей, которые смотрят в круглые/текстовые комбо.
Основной проблемой, которую я имел, был текст, который часто нарушал границы круга. Чтобы решить эту проблему, я решил использовать 4 div. Один прямоугольный контейнер, который задавал максимальные (фиксированные) границы круга. Внутри это будет div, который рисует круг с его шириной и высотой, установленной на 100%, поэтому изменение размера родителя изменяет размер фактического круга. Внутри этого будет еще один прямоугольный div, который, используя% s, создаст область текста, предотвращающую любой текст, выходящий из круга (по большей части) Затем, наконец, фактический div для текста и вертикального центрирования.
Это имеет смысл в качестве кода:
/* Main Container - this controls the size of the circle */
.circle_container
{
width : 128px;
height : 128px;
margin : 0;
padding : 0;
/* border : 1px solid red; */
}
/* Circle Main draws the actual circle */
.circle_main
{
width : 100%;
height : 100%;
border-radius : 50%;
border : 2px solid black; /* can alter thickness and colour of circle on this line */
margin : 0;
padding : 0;
}
/* Circle Text Container - constrains text area to within the circle */
.circle_text_container
{
/* area constraints */
width : 70%;
height : 70%;
max-width : 70%;
max-height : 70%;
margin : 0;
padding : 0;
/* some position nudging to center the text area */
position : relative;
left : 15%;
top : 15%;
/* preserve 3d prevents blurring sometimes caused by the text centering in the next class */
transform-style : preserve-3d;
/*border : 1px solid green;*/
}
/* Circle Text - the appearance of the text within the circle plus vertical centering */
.circle_text
{
/* change font/size/etc here */
font: 11px "Tahoma", Arial, Serif;
text-align : center;
/* vertical centering technique */
position : relative;
top : 50%;
transform : translateY(-50%);
}
<div class="circle_container">
<div class="circle_main">
<div class="circle_text_container">
<div class = "circle_text">
Here is an example of some text in my circle.
</div>
</div>
</div>
</div>
Конечно, вы должны использовать теги, чтобы сделать это. Один для создания круга, а другой для текста.
Здесь какой-то код может помочь вам
#circle {
background: #f00;
width: 200px;
height: 200px;
border-radius: 50%;
color:black;
}
.innerTEXT{
position:absolute;
top:80px;
left:60px;
}
<div id="circle">
<span class="innerTEXT"> Here a text</span>
</div>
Живой пример здесь http://jsbin.com/apumik/1/edit
Обновить
Здесь меньше поменьше с небольшими изменениями
Если это только одна строка текста, вы можете использовать свойство line-height с тем же значением, что и высота элемента:
height:100px;
line-height:100px;
Если текст состоит из нескольких строк, или если содержимое является переменным, вы можете использовать padding-top:
padding-top:30px;
height:70px;
Пример: http://jsfiddle.net/2GUFL/
Если вы используете Foundation 5 и Compass framework, вы можете попробовать это.
.sass input
$circle-width: rem-calc(25) !default;
$circle-height: $circle-width !default;
$circle-bg: #fff !default;
$circle-radius: 50% !default;
$circle-line-height: $circle-width !default;
$circle-text-align: center !default;
@mixin circle($cw:$circle-width, $ch:$circle-height, $cb:$circle-bg, $clh:$circle-line-height, $cta:$circle-text-align, $cr:$circle-radius) {
width: $cw;
height: $ch;
background: $cb;
line-height: $clh;
text-align: $cta;
@include inline-block;
@include border-radius($cr);
}
.circle-default {
@include circle;
}
.css output
.circle-default {
width: 1.78571rem;
height: 1.78571rem;
background: white;
line-height: 1.78571rem;
text-align: center;
display: -moz-inline-stack;
display: inline-block;
vertical-align: middle;
*vertical-align: auto;
zoom: 1;
*display: inline;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-ms-border-radius: 50%;
-o-border-radius: 50%;
border-radius: 50%;
}
Для меня только это решение работало для многострочного текста:
.circle-multiline {
display: table-cell;
height: 200px;
width: 200px;
text-align: center;
vertical-align: middle;
border-radius: 50%;
background: yellow;
}
Некоторые решения здесь не спомогли мне в маленьких кругах. Поэтому я сделал это решение, используя абсолютную позицию.
Использование SASS будет выглядеть так:
.circle-text {
position: relative;
display: block;
text-align: center;
border-radius: 50%;
> .inner-text {
display: block;
@extend .center-align;
}
}
.center-align {
position: absolute;
top: 50%;
left: 50%;
margin: auto;
-webkit-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
@mixin circle-text($size) {
width: $size;
height: $size;
@extend .circle-text;
}
И может быть использован как
#red-circle {
background-color: red;
border: 1px solid black;
@include circle-text(50px);
}
#green-circle {
background-color: green;
border: 1px solid black;
@include circle-text(150px);
}
Смотрите демонстрацию на https://codepen.io/matheusrufca/project/editor/DnYPMK
Смотрите фрагмент для просмотра выходного CSS
.circle-text {
position: relative;
display: block;
border-radius: 50%;
text-align: center;
min-width: 50px;
min-height: 50px;
}
.center-align {
position: absolute;
top: 50%;
left: 50%;
margin: auto;
-webkit-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
<div id="red-circle" class="circle-text">
<span class="inner-text center-align">Hey</span>
</div>
<div id="green-circle" class="circle-text">
<span class="inner-text center-align">Big size circle</span>
<div>
<style>
#red-circle {
background-color: red;
border: 1px solid black;
width: 60px;
height: 60px;
}
#green-circle {
background-color: green;
border: 1px solid black;
width: 150px;
height: 150px;
}
</style>
.circle {
width: 500px;
height: 500px;
border-radius: 50%;
font-size: 50px;
color: #fff;
line-height: 500px;
text-align: center;
background: #000
}
<div class="circle">Hello I am A CircleHello I am A CircleHello I am A CircleHello I am A CircleHello I am A CircleHello I am A CircleHello I am A CircleHello I am A CircleHello I am A Circle</div>
Получите это на странице YouTube, которая имеет действительно простую настройку. Абсолютно ремонтируемый и многоразовый.
.circle {
position: absolute;
top: 4px;
color: white;
background-color: red;
width: 18px;
height: 18px;
border-radius: 50%;
line-height: 18px;
font-size: 10px;
text-align: center;
cursor: pointer;
z-index: 999;
}
<div class="circle">2</div>
Один из способов сделать это - использовать flexbox, чтобы выровнять текст по середине. Способ, которым я нашел это, заключается в следующем:
HTML:
<div class="circle-without-text">
<div class="text-inside-circle">
The text
</div>
</div>
CSS
.circle-without-text {
border-radius: 50%;
width: 70vh;
height: 70vh;
background-color: red;
position: relative;
}
.text-inside-circle {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
Здесь plnkr: https://plnkr.co/edit/EvWYLNfTb1B7igoc3TZx?p=preview
Используя этот код, он также будет реагировать.
<div class="circle">ICON</div>
.circle {
position: relative;
display: inline-block;
width: 100%;
height: 0;
padding: 50% 0;
border-radius: 50%;
/* Just making it pretty */
-webkit-box-shadow: 0 4px 0 0 rgba(0, 0, 0, 0.1);
box-shadow: 0 4px 0 0 rgba(0, 0, 0, 0.1);
text-shadow: 0 4px 0 rgba(0, 0, 0, 0.1);
background: #38a9e4;
color: white;
font-family: Helvetica, Arial Black, sans;
font-size: 48px;
text-align: center;
}
Я сочетал ответы от других людей и float
и relative
дал мне результат, который мне нужен.
В HTML я использую div. Я использую его внутри li
для панели навигации.
.large-list-style {
float: left;
position: relative;
top: -8px;
border-radius: 50%;
margin-right: 8px;
background-color: rgb(34, 198, 200);
font-size: 18px;
color: white;
}
.large-list-style:before,
.large-list-style:after {
content: '\200B';
display:inline-block;
line-height:0;
padding-top: 50%;
padding-bottom: 50%;
}
.large-list-style:before {
padding-left: 16px;
}
.large-list-style:after {
padding-right: 16px;
}
Нарисуйте круг с текстом посередине с тегом HTML и без CSS
HTML, имеющий SVG-тег для этого. Вы можете следовать этому стандартному подходу, если вы не хотите использовать CSS.
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="white" />
Sorry, your browser does not support inline SVG.
<text fill="#000000" font-size="18" font-family="Verdana"
x="15" y="60">ASHISH</text>
</svg>