css: как нарисовать круг с текстом в середине?



Я нашел этот пример на StackOverflow:



нарисуйте круг, используя только css



это здорово. Но я хотел бы знать, как изменить этот пример, чтобы я мог включить текст в середине круга?



Я также нашел это: вертикальное и горизонтальное центрирование текста по кругу в CSS (например, значок уведомления iphone)



но по какой-то причине, он не работает для меня. Когда я создаю следующий тестовый код:



<div class="badge">1</div>


вместо круга я получаю овальную форму.
Я пытаюсь поиграть с кодом, чтобы увидеть, как я могу заставить его работать.

917   15  

15 ответов:

JSFiddle

.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-width-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>

для веб-дизайна, который мне недавно дали, мне нужно было решить центрированное и неизвестное количество текста в фиксированном круге, и я думал, что поделюсь решением здесь для других людей, которые смотрят на круг/текстовые комбо.

главным вопросом, который у меня был, был текст, который часто нарушал границы круга. Чтобы решить эту проблему, я в конечном итоге с помощью 4 дивов. Один прямоугольный контейнер, в котором указаны максимальные (фиксированные) границы круга. Внутри этого будет 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>			

вы можете раскомментировать цвета границы на контейнере divs, чтобы увидеть, как это сдерживает.

вещи, о которых нужно знать: Вы все еще можете нарушить границы круга, если вы помещаете слишком много текста или используете слова/неразрывный текст, которые слишком длинны. Он по-прежнему не подходит для полностью неизвестного текста (например, ввода пользователем), но лучше всего работает, когда вы смутно знаете, какой самый большой объем текста вам нужно сохранить, и установите размер круга и размеры шрифта соответственно. Вы можете установить текстовый контейнер div, чтобы скрыть любое переполнение, конечно, но это может просто выглядеть "сломанным" и не является заменой для фактического учета максимального размера правильно в вашем дизайне.

надеюсь, что это полезно для кого-то! HTML / CSS-это не моя основная дисциплина, поэтому я уверен, что ее можно улучшить!

Я думаю, что вы хотите написать текст в овале или круге? почему не этот?

<span style="border-radius:50%; border:solid black 1px;padding:5px">Hello</span>

конечно, вы должны использовать теги для этого. Один для создания круга, а другой для текста.

здесь какой-то код может помочь вам

#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

обновление

здесь меньше, меньше с небольшими изменениями

http://jsbin.com/apumik/3/edit

Если это только одна строка текста, вы можете использовать свойство line-height с тем же значением, что и высота элемента:

height:100px;
line-height:100px;

Если текст имеет несколько строк, или если содержимое является переменным, вы можете использовать padding-top:

padding-top:30px;
height:70px;

Пример:http://jsfiddle.net/2GUFL/

Если вы используете Foundation 5 и Compass framework, вы можете попробовать это.

.ввод Сасс

$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

.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;
}

некоторые из решений здесь не работают хорошо для меня на небольших кругах. Поэтому я сделал это решение, используя абсолютное положение ol.

использование 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: '0B';
        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;
    }

Comments

    Ничего не найдено.