简体   繁体   English

如何使用 CSS 垂直对齐文本?

[英]how do i align text vertically using CSS?

<div style='height:200px;'>
SOME TEXT
</div>

how do i align "SOME TEXT" at the bottom of the div using CSS without padding?我如何使用 CSS 在没有填充的情况下在 div 底部对齐“SOME TEXT”?

The absolute easiest way, though not-exactly using your code example, would be:尽管不完全使用您的代码示例,但绝对最简单的方法是:

div {height: 400px;
    width: 50%;
    margin: 0 auto;
    background-color: #ffa;
    position: relative;
    }

div p   {position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    }

html html

<div id="container">
<p>SOME TEXT</p>
</div>

Wrap your text in an element, anything from <p> , <span> , <div> ...whatever, and position that element at the bottom of its container.将您的文本包裹在一个元素中,任何来自<p><span><div>任何内容,并将该元素放置在其容器的底部。

You can't do it in a simple way, at least not cross browser.你不能以简单的方式做到这一点,至少不能跨浏览器。
You can use the display: table;您可以使用显示:表格; vertical-align: center;垂直对齐:居中;
You can use JS/ CSS expressions.您可以使用 JS/CSS 表达式。
You can have another element inside the div, and position it absolute in relation to the div:您可以在 div 中放置另一个元素,并将其相对于 div 进行绝对定位:

<div style='position:relative;'>
    <div style='position: absolute; bottom:0;>
            My Text
    </div>
</div>

But really, as much as I hate to say, Tables is the KISS here ( if you need to veritcaly center it).但实际上,正如我不想说的那样,Tables 是这里的 KISS(如果您需要将其真正居中)。

TDs can vertically align text with vertical-align, but this does not work on DIVs. TD 可以使用 vertical-align 垂直对齐文本,但这不适用于 DIV。 It is not considered good style to use tables to vertically align elements.使用表格垂直对齐元素不被认为是好的风格。

You cannot vertical-align text within DIVs with CSS.您不能使用 CSS 在 DIV 中垂直对齐文本。 You can only use padding, margin, or absolute and fixed positioning to align an text vertically.您只能使用填充、边距或绝对和固定定位来垂直对齐文本。

If you use absolute positioning well, you can vertically align the text by vertically aligning a container that the text is in. However, absolutely positioned elements do not take up "space" within their container, which means you have to set a margin or padding to offset that space in the container.如果绝对定位使用得当,您可以通过垂直对齐文本所在的容器来垂直对齐文本。但是,绝对定位的元素不会占用其容器内的“空间”,这意味着您必须设置边距或填充来抵消容器中的空间。

Eg:例如:

HTML: HTML:

<div id="container">
  <span id="text">Some text, Some text, Some text, </span>
</div>

CSS: CSS:

#id {
  position:relative;
  margin-bottom: 100px;
}

#text {
  position:absolute;
  bottom:0;
  height: 100px;
  overflow:hidden;
}
# id{
    display:table-cell; 
    vertical-align:bottom;
    }

Using flex, supported in most recent browsers使用 flex,大多数浏览器都支持

 div { align-items: center; background: red; display: flex; /* Uncomment to align it horizontally */ /* justify-content: center; */ }
 <div style='height:200px;'> SOME TEXT </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM