Css set text baseline

vertical-align

Свойство CSS vertical-align описывает вертикальное позиционирование строчных (inline), строчно-блочных (inline-block) элементов или ячеек таблицы (table-cell).

/* ключевые значения */ vertical-align: baseline; vertical-align: sub; vertical-align: super; vertical-align: text-top; vertical-align: text-bottom; vertical-align: middle; vertical-align: top; vertical-align: bottom; /* значения длины () */ vertical-align: 10em; vertical-align: 4px; /* процентные значения () */ vertical-align: 20%; /* глобальные значения */ vertical-align: inherit; vertical-align: initial; vertical-align: unset; 

Свойство vertical-align может использоваться в двух контекстах:

  • Для вертикального позиционирования области строчного элемента внутри области содержащей его строки. Например, с помощью него можно вертикально позиционировать в строке текста:
p> top:img style="vertical-align:top" src="star.png"/> middle:img style="vertical-align:middle" src="star.png"/> bottom:img style="vertical-align:bottom" src="star.png"/> super:img style="vertical-align:super" src="star.png"/> sub:img style="vertical-align:sub" src="star.png"/> p> p> text-top:img style="vertical-align:text-top" src="star.png"/> text-bottom:img style="vertical-align:text-bottom" src="star.png"/> 0.2em:img style="vertical-align:0.2em" src="star.png"/> -1em:img style="vertical-align:-1em" src="star.png"/> 20%:img style="vertical-align:20%" src="star.png"/> -100%:img style="vertical-align:-100%" src="star.png"/> p> 
#*  box-sizing: border-box; > img  margin-right: 0.5em; > p  height: 3em; padding: 0 .5em; font-family: monospace; text-decoration: underline overline; margin-left: auto; margin-right: auto; width: 80%; > 
table> tr> td style="vertical-align: baseline">baselinetd> td style="vertical-align: top">toptd> td style="vertical-align: middle">middletd> td style="vertical-align: bottom">bottomtd> td> p>Существует теория, которая утверждает, что если однажды кто-нибудь доподлинно выяснит, что такое и для чего нужна Вселенная, она тотчас же исчезнет, и вместо неё появится нечто ещё более причудливое и необъяснимое.p> p>Существует и другая теория, согласно которой это уже случилось.p> 
table  margin-left: auto; margin-right: auto; width: 80%; > table, th, td  border: 1px solid black; > td  padding: 0.5em; font-family: monospace; > 

Примечание: свойство vertical-align применяется только к строчным элементам и элементам ячеек таблицы: его нельзя использовать для вертикального позиционирования блочных элементов.

Начальное значение baseline
Применяется к строчным элементам и ячейкам таблиц. Это также применяется к ::first-letter и ::first-line .
Наследуется нет
Проценты относятся к line-height самого элемента
Обработка значения для процентов и значений длин, абсолютных длин или ключевых слов, если указаны
Animation type длина

Синтаксис

Свойство vertical-align задаётся одним из ключевых значений, указанных ниже.

Значения для строчных элементов

Значения относительно родительского элемента

Данные значения позиционируют элемент по вертикали относительно родительского элемента:

Выравнивает базовую линию элемента с базовой линией родительского элемента. Базовая линия некоторых замещаемых элементов (en-US) , таких как (en-US), не описана в спецификации HTML, что означает, что их поведение при указании данного ключевого слова может отличаться в зависимости от браузера.

Выравнивает базовую линию элемента с базовой линией подстрочного индекса своего родителя.

Выравнивает базовую линию элемента с базовой линией надстрочного индекса своего родителя.

Выравнивает верхний край элемента с верхним краем шрифта родительского элемента.

Выравнивает нижний край элемента с нижним краем шрифта родительского элемента.

Выравнивает середину элемента с базовой линией своего родителя плюс половина от его высоты (x-height).

Поднимает базовую линию элемента на указанную величину над базовой линией родительского элемента. Допустимы отрицательные значения.

Поднимает базовую линию элемента на указанную в процентах величину (вычисляется относительно значения свойства line-height ) над базовой линией родительского элемента. Допустимы отрицательные значения.

Значения относительно строки

Следующие значения позиционируют элемент по вертикали относительно всей строки:

Выравнивает верхний край элемента и его потомков с верхним краем всей строки.

Выравнивает нижний край элемента и его потомков с нижним краем всей строки.

Для элементов, у которых нет базовой линии, вместо неё используется нижняя граница внешнего отступа (margin).

Значения для ячеек таблицы

baseline (и sub , super , text-top , text-bottom , , и )

Выравнивает базовую линию ячейки с базовой линией всех остальных ячеек этой строки, которые выравнены относительно базовой линии.

Выравнивает верхнюю границу внутреннего отступа (padding) ячейки с верхним краем строки таблицы.

Выравнивает внутреннее поле (padding box) ячейки по центру относительно строки таблицы.

Выравнивает нижнюю границу внутреннего отступа (padding) ячейки с нижним краем строки таблицы.

Допустимы отрицательные значения.

Формальный синтаксис

vertical-align =
[ (en-US) first | (en-US) last ] (en-US) || (en-US)
|| (en-US)

Пример

HTML

div>Изображение img src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по умолчанию.div> div>Изображение img class="top" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по верхнему краю.div> div>Изображение img class="bottom" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по нижнему краю.div> div>Изображение img class="middle" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по центру.div> 

CSS

img.top  vertical-align: text-top; > img.bottom  vertical-align: text-bottom; > img.middle  vertical-align: middle; > 

Результат

Спецификации

Совместимость с браузерами

BCD tables only load in the browser

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

Found a content problem with this page?

This page was last modified on 11 февр. 2023 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Align text baseline with a button in CSS

problem representation

I would like to achieve one of the two alignments represented on this image: . CSS3 is ok or even better if it makes things simpler. My main problem is that I managed to align one div containing the text with the button, but the text itself is aligned with the top of the div and not the bottom.

2 Answers 2

set for the button parent,
where, as you can see, line-height matches the element height
and will align both texts at the element’s ( p ) center. Otherwise, the button, being an inline element by default, it’s subject to manipulations using the CSS property vertical-align: which basically aligns all *inline** elements vertically inside a block level element using this typography terms:

vertical-align: baseline; vertical-align: sub; vertical-align: super; vertical-align: text-top; vertical-align: text-bottom; vertical-align: middle; vertical-align: top; vertical-align: bottom; vertical-align: 10em; vertical-align: 4px; vertical-align: 20%; 

exactly, you can even manually adjust the alignment using PX / -PX and %

I’ve encountered some issues using line-height on Android browsers (), so sometimes the right solution was to play with the parent padding * and vertical-align rather than the inner children’s alignments (with line-height).

*(note: padding for block elements is more consistent than (top, bottom) used on inner inline elements.)

Источник

How to absolutely position the baseline of text in HTML

a diagram

I’m puzzled by the following problem. I wish to (absolutely) position the baseline of some piece of HTML text at a certain y-coordinate, while the text should be starting at a certain x-coordinate. The following diagram clearly demonstrates the issue. So I basically want to control where the point (x,y), henceforth called the «basepoint», in the diagram is located on the screen, relative to the top-left corner of the BODY of the document or some DIV. Important: I don’t know beforehand what the font-family or font-size of the text is. This is important, because I don’t want to change all the positions in my CSS whenever I change fonts. In the following code, I try to position the basepoint at (200,100), but instead it positions the top-left of the DIV at that point.

So how should I modify this code? Should I use the vertical-align property of the enclosing DIV? (I tried, but couldn’t get the desired result). Thanks for any useful replies.

5 Answers 5

JsFiddle. The basepoint is aligned to (100, 120).

jsFiddle Goofy (and crazy ugly/hacky), but it works.

  
css=powerful
 body < margin: 0px; >#spacer < float: left; width: 190px; height: 100px; background-color: red; >#baseline < visibility: hidden; >#text < float: left; background-color: yellow; font-family: helvetica, arial; /* may vary */ font-size: 60px; /* may vary */ >

Edit I guess, really, it’s all about the image. So you could just simplify and use a transparent spacer gif. Still stupid hacky, I know. jsFiddle

Источник

CSS set baseline of inline-block element manually and have it take the expected height

I’m designing a sea-sky component. I’d like to have it’s baseline at sea-level. Here’s an attempt that’s rendering correctly.

The trick here is to set a negative bottom and use a padding to have the .out bottom at the expected position. Here’s what happens without the padding.

However, using multiple such component would require setting the padding to the max of all the bottom of the components which are on the last line. This is not feasible. Is there a way to do without the padding-bottom ?

1 Answer 1

The problem is that you use bottom: -30px . Yes, aligns the sea with the text, but breaks the layout.

The baseline of an ‘inline-block’ is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its ‘overflow’ property has a computed value other than ‘visible’, in which case the baseline is the bottom margin edge.

That is, you only need to fill the sky part with some in-flow content. Since the sea part is already out-of-flow, it won’t affect the baseline. Therefore, you can insert a pseudo-element is .outer which takes the remaining height left by .inner :

.out < display: inline-block; background-color: yellow; >.outer < display: inline-block; background-color: cyan; width: 100px; height: 100px; position: relative; >.outer::before < content: ''; display: inline-block; height: calc(100% - 30px); >.inner

To avoid that calc(100% — 30px) you can also use flexbox:

.out < display: inline-block; background-color: yellow; >.outer < display: inline-flex; flex-direction: column; background-color: cyan; width: 100px; height: 100px; >.outer::before < content: ''; flex: 1; >.inner

But I think the CSS WG hasn’t completely decided how baselines in orthogonal flows should behave, so I would recommend calc(100% — 30px) for now.

Источник

Читайте также:  Wordpress wp login php error
Оцените статью