Как изменить высоту букв html

I want to change not the font-size of text, but two independent properties relative to its width and height. So, by applying font-width: 50% to this element: the text would be stretched to half: Is

I want to change not the font-size of text, but two independent properties relative to its width and height.
So, by applying font-width: 50% to this element:

enter image description here

the text would be stretched to half:

enter image description here

Is this possible to do using CSS?

asked Oct 4, 2015 at 10:05

cabralpinto's user avatar

cabralpintocabralpinto

1,7443 gold badges13 silver badges29 bronze badges

4

CSS transform has the scale function for this:

p {
  display: inline-block;
  font-size: 32px;
  transform: scale(.5, 1);
}
<p>This is text.</p>

Use the two numbers in the function for X- and Y-axis respectively.

answered Oct 4, 2015 at 10:14

Sebastian Simon's user avatar

Sebastian SimonSebastian Simon

17.7k7 gold badges55 silver badges73 bronze badges

0

You can try scaling the font in x direction.

p{
    -webkit-transform: scaleX(0.5);
    transform: scaleX(0.5);
}

Sebastian Simon's user avatar

answered Oct 4, 2015 at 10:17

Aakash's user avatar

AakashAakash

1,7411 gold badge14 silver badges21 bronze badges

The closest thing I can find is font-weight

It accepts not only bold,normal but also numeric values. 100-900 in 100 increments.

 . Paragraph {font-weight :700;}

This combined with height properties should help but will not give you complete solution

Also look at spacing properties as you can reduce the the width of the words that way

  letter-spacing: 2px; 

answered Oct 4, 2015 at 10:23

Fintan Creaven's user avatar

2

Using a svg text with preserveAspectRatio="none" allow text deformations and very precise positioning.

To adjust, It’s all about the viewBox. The rendering stays natively responsive to browser resizes.

The text stays select able.

.title {
  width: 540px;
  height: 40px
}

.content {
  width: 300px;
  height: 400px
}

.side {
  width: 270px;
  height: 100px;
  color: red;
  position: absolute;
  right: 30px;
  top: 160px;
  transform: rotate(44deg)
}
<div class="title">
  <svg preserveAspectRatio="none" x="0" y="30" viewBox="0 0 100 15" width="100%" height="100%">
   <foreignObject x="5" y="1" height="100%" width="100%">
      <div>
        Hello world!
       </div>
     </foreignObject>    
  </svg>
</div>

<div class="content">
  <svg preserveAspectRatio="none" x="0" y="30" viewBox="0 0 400 200" width="100%" height="100%">
    <foreignObject x="55" y="15" height="100%" width="80%">
      <div>
       The best way to use a hello cheer for introducing players is to have one cheerleader use a megaphone or loudspeaker to announce the players names and stats.
       </div>
     </foreignObject>     
  </svg>
</div>


<div class="side">
  <svg preserveAspectRatio="none" x="0" y="30" viewBox="0 0 100 100" width="100%" height="100%">
    <foreignObject x="5" y="15" height="200%" width="100%">
      <div>
       NOW WITH COLORS!
       </div>
     </foreignObject>     
  </svg>
</div>

Tip: For complex stuffs, flyers making, using the cm css unit works very well.

answered Sep 30, 2020 at 22:07

NVRM's user avatar

NVRMNVRM

10.6k1 gold badge82 silver badges85 bronze badges

3

Серёжа Сыроежкин

Серёжа СыроежкинКопирайтер

Размер шрифта на сайте можно задать как при помощи HTML, так и с помощью CSS. Рассмотрим оба варианта.

Задание размера шрифта с помощью HTML

Размер шрифта на странице можно определить при помощи тега font HTML. В статье Цвет шрифта HTML мы уже рассматривали тег font и его атрибуты. Одним из атрибутов этого тега является size, который и позволяет установить размер шрифта. Применяется он следующим образом:

Конструктор сайтов <font size="7">"Нубекс"</font>

Size может принимать значения от 1 до 7 (по умолчанию равен 3, что соответствует 13,5 пунктам для шрифта Times New Roman). Другой вариант задания атрибута – “+1” или “-1”. Это означает, что размер будет изменен относительно базового на 1 пункт больше или меньше, соответственно.

Приведенный способ довольно прост в использовании и незаменим при необходимости изменения размера шрифта небольшого куска текста. В остальных случаях рекомендуется определять стиль текста с помощью CSS.

Устанавливаем размер шрифта при помощи CSS

В CSS для изменения размера шрифта применяется свойство font-size, которое применяется следующим образом:

<html>
 <head>
  <title>Меняем размер шрифта при помощи CSS</title>
   <style>
	.nubex {
	font-size: 14px;
	}
   </style>
 </head>
 <body>
	<div class="nubex">Шрифты HTML-блока div класса nubex получают размер 14px при помощи свойства font size.</div>
 </body>
</html>

В приведенном примере размер шрифта устанавливается в пикселях. Но существуют и другие способы задания размера:

  • large, small, medium — задают абсолютный размер (маленький, средний, большой). Также могут применяться значения экстра-маленький (x-small, xx-small), экстра-большой (x-large, xx-large).
  • larger, smaller — задают относительный размер (меньше или больше относительно родительского элемента).
  • 100% — задается относительный размер (в процентах относительно родительского). Например:
    h1 {
    	font-size: 180%;
    }

    Это означает, что размер тега H1 будет составлять 180% от базового размера шрифта.

  • Другие варианты задания относительного размера:
    • 5ex — означает, что размер составит 5 высот буквы x от базового шрифта;
    • 14pt — 14 пунктов;
    • 22px — 22 пикселя;
    • 1vw — 1% от ширины окна браузера;
    • 1vh — 1% от высоты окна браузера;

Смотрите также:

The font-size CSS property sets the size of the font. Changing the font size also updates the sizes of the font size-relative <length> units, such as em, ex, and so forth.

Try it

Syntax

/* <absolute-size> values */
font-size: xx-small;
font-size: x-small;
font-size: small;
font-size: medium;
font-size: large;
font-size: x-large;
font-size: xx-large;
font-size: xxx-large;

/* <relative-size> values */
font-size: smaller;
font-size: larger;

/* <length> values */
font-size: 12px;
font-size: 0.8em;

/* <percentage> values */
font-size: 80%;

/* math value */
font-size: math;

/* Global values */
font-size: inherit;
font-size: initial;
font-size: revert;
font-size: revert-layer;
font-size: unset;

The font-size property is specified in one of the following ways:

  • As one of the absolute-size, relative-size or math keywords
  • As a <length> or a <percentage>, relative to the element’s font size.

Values

xx-small, x-small, small, medium, large, x-large, xx-large, xxx-large

Absolute-size keywords, based on the user’s default font size (which is medium).

larger, smaller

Relative-size keywords. The font will be larger or smaller relative to the parent element’s font size, roughly by the ratio used to separate the absolute-size keywords above.

<length>

A positive <length> value. For most font-relative units (such as em and ex), the font size is relative to the parent element’s font size.

For font-relative units that are root-based (such as rem), the font size is relative to the size of the font used by the <html> (root) element.

<percentage>

A positive <percentage> value, relative to the parent element’s font size.

Note: To maximize accessibility, it is generally best to use values that are relative to the user’s default font size.

  • math
    Experimental

    Special mathematical scaling rules must be applied when determining the computed value of the font-size property.

Description

There are several ways to specify the font size, including keywords or numerical values for pixels or ems. Choose the appropriate method based on the needs of the particular web page.

Keywords

Keywords are a good way to set the size of fonts on the web. By setting a keyword font size on the <body> element, you can set relative font-sizing everywhere else on the page, giving you the ability to easily scale the font up or down on the entire page accordingly.

Pixels

Setting the font size in pixel values (px) is a good choice when you need pixel accuracy. A px value is static. This is an OS-independent and cross-browser way of literally telling the browsers to render the letters at exactly the number of pixels in height that you specified. The results may vary slightly across browsers, as they may use different algorithms to achieve a similar effect.

Font sizing settings can also be used in combination. For example, if a parent element is set to 16px and its child element is set to larger, the child element displays larger than the parent element on the page.

Note: Defining font sizes in px is not accessible, because the user cannot change the font size in some browsers. For example, users with limited vision may wish to set the font size much larger than the size chosen by a web designer. Avoid using them for font sizes if you wish to create an inclusive design.

Ems

Using an em value creates a dynamic or computed font size (historically the em unit was derived from the width of a capital «M» in a given typeface.). The numeric value acts as a multiplier of the font-size property of the element on which it is used. Consider this example:

In this case, the font size of <p> elements will be double the computed font-size inherited by <p> elements. By extension, a font-size of 1em equals the computed font-size of the element on which it is used.

If a font-size has not been set on any of the <p>‘s ancestors, then 1em will equal the default browser font-size, which is usually 16px. So, by default 1em is equivalent to 16px, and 2em is equivalent to 32px. If you were to set a font-size of 20px on the <body> element say, then 1em on the <p> elements would instead be equivalent to 20px, and 2em would be equivalent to 40px.

In order to calculate the em equivalent for any pixel value required, you can use this formula:

em = desired element pixel value / parent element font-size in pixels

For example, suppose the font-size of the <body> of the page is set to 16px. If the font-size you want is 12px, then you should specify 0.75em (because 12/16 = 0.75). Similarly, if you want a font size of 10px, then specify 0.625em (10/16 = 0.625); for 22px, specify 1.375em (22/16).

The em is a very useful unit in CSS since it automatically adapts its length relative to the font that the reader chooses to use.

One important fact to keep in mind: em values compound. Take the following HTML and CSS:

html {
  font-size: 100%;
}
span {
  font-size: 1.6em;
}
<div>
  <span>Outer <span>inner</span> outer</span>
</div>

The result is:

Assuming that the browser’s default font-size is 16px, the words «outer» would be rendered at 25.6px, but the word «inner» would be rendered at 40.96px. This is because the inner <span>‘s font-size is 1.6em which is relative to its parent’s font-size, which is in turn relative to its parent’s font-size. This is often called compounding.

Rems

rem values were invented in order to sidestep the compounding problem. rem values are relative to the root html element, not the parent element. In other words, it lets you specify a font size in a relative fashion without being affected by the size of the parent, thereby eliminating compounding.

The CSS below is nearly identical to the previous example. The only exception is that the unit has been changed to rem.

html {
  font-size: 100%;
}
span {
  font-size: 1.6rem;
}

Then we apply this CSS to the same HTML, which looks like this:

<span>Outer <span>inner</span> outer</span>

In this example, the words «outer inner outer» are all displayed at 25.6px (assuming that the browser’s font-size has been left at the default value of 16px).

Ex

Like the em unit, an element’s font-size set using the ex unit is computed or dynamic. It behaves in exactly the same way, except that when setting the font-size property using ex units, the font-size equals the x-height of the first available font used on the page. The number value multiplies the element’s inherited font-size and the font-size compounds relatively.

See the W3C Editor’s Draft for a more detailed description of font-relative length units such as ex.

Formal definition

Initial value medium
Applies to all elements. It also applies to ::first-letter and ::first-line.
Inherited yes
Percentages refer to the parent element’s font size
Computed value as specified, but with relative lengths converted into absolute lengths
Animation type a length

Formal syntax

Examples

Setting font sizes

CSS

.small {
  font-size: xx-small;
}
.larger {
  font-size: larger;
}
.point {
  font-size: 24pt;
}
.percent {
  font-size: 200%;
}

HTML

<h1 class="small">Small H1</h1>
<h1 class="larger">Larger H1</h1>
<h1 class="point">24 point H1</h1>
<h1 class="percent">200% H1</h1>

Result

Specifications

Specification
CSS Fonts Module Level 4
# font-size-prop

Browser compatibility

BCD tables only load in the browser

See also

HTML Font Size – How to Change Text Size with an HTML Tag

When you add text to your HTML file with an HTML tag, you won’t always want the text to remain the default size. You’ll want to be able to adjust how the text displays in the browser.

In this article, you will learn how to change the text size with an HTML tag.

Before you proceed, it is essential to know that there is only one way we can do this: through CSS’s font-size property. We can use the font-size property through inline, internal, or external styling.

In the past, we could adjust text size within our HTML tag without using CSS. But that was before HTML5. Then we added text using the <font> tag, which can take in an attribute of size as seen below:

<font size="5">  
    Hello World 
</font>  

This size attribute can take in value from 1-7 in which the text size increases from 1 to 7. But like I said, this has long been depreciated, and most people don’t even know it existed.

In case you are in a rush to see how you can change the size of your text, then here it is:

// Using inline CSS
<h1 style="font-size: value;"> Hello World! </h1>

// Using internal/external CSS
selector {
    font-size: value;
}

Suppose you are not in a rush. Let’s briefly dive right in.

How to Change Text Size With Inline CSS

Inline CSS allows you to apply styles to specific HTML elements. This means we are putting CSS into an HTML tag directly. We use the style attribute, which now holds all our styling.

<h1 style="...">Hello World!</h1>

We use the font-size property alongside our value to change the text size using inline CSS. This value can use any of your preferred CSS units such as em, px, rem, and so on.

<h1 style="font-size:4em; "> Hello World! </h1>
<p style="font-size:14px; "> Any text whose font we want to change </p>

A perfect syntax would be:

<TEXT-TAG style="font-size:value;"> ... </TEXT-TAG>

How to Change Text Size With Internal or External CSS

The approach you use to change text size in internal and external CSS styling is similar, since you use a selector. The general syntax for this is:

selector {
    font-size: value;
}

The selector can either be our HTML tag or maybe a class or an ID. For example:

// HTML
<p> Any text whose font we want to change </p>

// CSS
p {
    font-size: 14px;
}

Or we could use a class:

// HTML
<p class="my-paragraph" > Any text whose font we want to change </p>

// CSS
.my-paragraph {
    font-size: 14px;
}

Wrapping Up

In this article, you learned how to change the font/text size of an HTML element using CSS. You also saw how developers did it before the introduction of HTML5.

Also, keep in mind that it’s always better to style your HTML elements using internal or external styling, as it offers a lot of flexibility compared to inline styling.

For example, you can make use of one CSS class for all your p tags rather than having to add inline styles to all your p tag elements.

Using inline styles is not considered best practice because it results in a lot of repetition – you cannot reuse the styles elsewhere. To learn more, you can read my article on Inline Style in HTML.

I hope this tutorial gives you the knowledge to change the size of your HTML text so you can make it look better.

Have fun coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Internet Explorer Chrome Opera Safari Firefox Android iOS
6.0+ 8.0+ 1.0+ 3.5+ 1.0+ 1.0+ 1.0+ 1.0+

Краткая информация

Значение по умолчанию medium
Наследуется Да
Применяется Ко всем элементам
Ссылка на спецификацию http://www.w3.org/TR/CSS21/fonts.html#propdef-font-size

Версии CSS

CSS 1 CSS 2 CSS 2.1 CSS 3

Описание

Определяет размер шрифта элемента. Размер может быть установлен несколькими
способами. Набор констант (xx-small, x-small, small,
medium, large, x-large, xx-large) задает размер, который называется абсолютным.
По правде говоря, они не совсем абсолютны, поскольку зависят от настроек браузера
и операционной системы.

Другой набор констант (larger, smaller)
устанавливает относительные размеры шрифта. Поскольку размер унаследован от
родительского элемента, эти относительные размеры применяются к родительскому
элементу, чтобы определить размер шрифта текущего элемента.

В конечном итоге, размер шрифта сильно зависит от значения свойства font-size у родителя элемента.

Сам размер шрифта определяется как высота от базовой линии до верхней границы кегельной площадки, как показано на рис. 1.

Размер шрифта

Рис. 1. Размер шрифта

Синтаксис

font-size: абсолютный размер | относительный размер | значение | проценты | inherit

Значения

Для задания абсолютного размера используются следующие значения: xx-small,
x-small, small, medium,
large, x-large, xx-large.
Их соответствие с размером шрифта в HTML приведено в табл. 1.

Табл. 1. Размер шрифта в CSS и HTML

CSS xx-small x-small small medium large x-large xx-large  
HTML 1   2 3 4 5 6 7

Относительный размер шрифта задается значениями larger и smaller.

Также разрешается использовать любые допустимые единицы CSS: em
(высота шрифта элемента), ex (высота символа х),
пункты (pt), пикселы (px),
проценты (%) и др. За 100% берется размер шрифта
родительского элемента. Отрицательные значения не допускаются.

inherit
Наследует значение родителя.

Пример

HTML5CSS2.1IECrOpSaFx

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>font-size</title>
  <style>
   h1 {
    font-family: 'Times New Roman', Times, serif; /* Гарнитура текста */ 
    font-size: 250%; /* Размер шрифта в процентах */ 
   } 
   p {
    font-family: Verdana, Arial, Helvetica, sans-serif; 
    font-size: 11pt; /* Размер шрифта в пунктах */ 
   }
  </style>
 </head> 
 <body> 
  <h1>Duis te feugifacilisi</h1>
  <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem 
  nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. 
  Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit 
  lobortis nisl ut aliquip ex ea commodo consequat.</p>
 </body>
</html>

Результат данного примера показан на рис. 1.

Применение свойства font-size

Рис. 2. Применение свойства font-size

Объектная модель

[window.]document.getElementById(«elementID«).style.fontSize

Браузеры

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit.

Высота шрифта

Последнее обновление: 21.04.2016

Для установки размера шрифта используется свойство font-size:

div{
	font-size: 18px;
}

В данном случае высота шрифта составит 18 пикселей. Пиксели представляют наиболее часто используемые единицы измерения. Чтобы задать значение в пикселях, после самого значения идет сокращение «px».

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

Базовый стиль для разных элементов текста отличается: если для параграфов это 16 пикселей, то для заголовков h1 это 32 пикселя, для заголовков h2 — 24 пикселя и т..д.

Для измерения шрифта также можно использовать самые разные единицы измерения.

Ключевые слова

В CSS имеется семь ключевых слов, которые позволяют назначить размер шрифта относительно базового:

  • medium: базовый размер шрифта браузера (16 пикселей)

  • small: 13 пикселей

  • x-small: 10 пикселей

  • xx-small: 9 пикселей

  • large: 18 пикселей

  • x-large: 24 пикселя

  • xx-large: 32 пикселя

Например:

font-size: x-large;

Проценты

Проценты позволяют задать значение относительно базового или унаследованного шрифта. Например:

font-size: 150%;

В данном случае высота шрифта будет составлять 150% от базового, то есть 16px * 1,5 = 24px

Наследование шрифта может изменить финальное значение. Например, следующую ситуацию:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Шрифты в CSS3</title>
		
        <style>
			div {font-size: 10px;}
			p {font-size: 150%;}
        </style>
    </head>
    <body>
	<div>
		<p>Однажды в студеную зимнюю пору</p>
	</div>
    </body>
</html>

Здесь элемент p наследует от контейнера — блока div шрифт высотой в 10 пикселей. То есть 10 пикселей теперь будет базовым для параграфа.

Далее для элемента p определяется новая высота шрифта в 150%. Это значит, что финальная высота будет равна 10px * 1,5 = 15px.

Единица еm

Единица измерения еm во многом эквивалентна процентам. Так, 1em равен 100%, .5em равно 50% и т.д.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить высоту букв css
  • Как изменить высоту блока через js
  • Как изменить высоту input
  • Как изменить высоту html страницы
  • Как изменить высоту grid ячейки

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии