简体   繁体   English

通过下划线和上划线的中心垂直居中

[英]Vertically center text by its underline and overline's center

I want to vertically center a text by its underline and overline. 我想通过下划线和上划线使文本垂直居中。 The text element is inside a div that is absolutely positioned and has an unknown (variable) height. 文本元素位于div内,该div绝对定位并且高度未知(可变)。 The text's font size and horizontal position also have to be variable. 文本的字体大小和水平位置也必须可变。

In other words: I want to position the text so that the center between underline and overline is exactly at the center of the containing div. 换句话说:我想放置文本,以便下划线和上划线之间的中心恰好位于包含div的中心。

Additionally, I want to display a rectangle (using a div) in front of the text: 另外,我想在文本前面显示一个矩形(使用div):

<div class="container">
  <div class="rectangle"></div>
  <div class="text">Text</div>
</div>

Here's an example: http://codepen.io/zabbarob/pen/CHxLe 这是一个示例: http : //codepen.io/zabbarob/pen/CHxLe

* { margin: 0; padding: 0; border: 0; }

.container {
  position: absolute; top: 5px; height: 25px;
  zoom: 800%; /* debugging */
  vertical-align: middle;
}

.rectangle {
  display: inline-block;
  width: 50px; height: 100%;
  background-color: green;
}

.text {
  display: inline-block;
  text-decoration: underline overline;
  font-size: 20px;
  position: absolute; left: 50px;
  background: lightgreen;
  /* center vertically by underline and overline */
  top: 0; bottom: 0;
  line-height: 25px;
}

Hmm, rather than using an actual overline/underline (which could be a bit of a headache to customize), have you considered mimicking it using border top/bottom instead? 嗯,您是否考虑过使用边框的顶部/底部来模仿它,而不是使用实际的上划线/下划线(可能难以自定义)? So you could modify your CSS definition for text as follows: 因此,您可以如下修改文本的CSS定义:

.text {
    display: inline-block;
    /*text-decoration: underline overline;*/
    font-size: 20px;
    position: absolute; left: 50px;
    background: lightgreen;
    /* center vertically by underline and overline */
    top: 0; bottom: 0;
    line-height: 23px; /* Height of the element beside it, minus 2px for the borders */
    border-top:1px solid #000;
    border-bottom:1px solid #000;
}

Here's a modified CodePen to demonstrate. 这是修改后的CodePen演示。 Depending on your requirements, this may not be optimal (for example, border scales with zoom, whereas underline does not), but it does at least give you a different way of approaching the problem. 根据您的要求,这可能不是最佳选择(例如,带缩放的边框比例,而下划线则不是),但是它至少为您提供了解决问题的另一种方法。

Hope this helps! 希望这可以帮助! Let me know if you have any questions. 如果您有任何疑问,请告诉我。

Have you tried using the methods outlined here: http://css-tricks.com/centering-in-the-unknown/ ? 您是否尝试过使用此处概述的方法: http : //css-tricks.com/centering-in-the-unknown/

Always works for me. 永远为我工作。

Hope this helps 希望这可以帮助

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

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