如何以响应的方式(不断地)居中文本?

Posted

技术标签:

【中文标题】如何以响应的方式(不断地)居中文本?【英文标题】:How can I center text (constantly) in a responsive manner? 【发布时间】:2021-11-11 21:49:40 【问题描述】:

我对编码很陌生。我正在学习 html 和 CSS。我想知道如何使这个标题和副标题以四种形式因素(我精确的尺寸)居中。

我不知道为什么使用 white-spaceno wrap 没有帮助:(

 .text-block 
        position: absolute;
        color: white;
        top: 10px;
        right: 50vh;
        left: 50vh;
        white-space:nowrap;
        
    
    
    
    
    .thecloud 
      background: URL("https://picsum.photos/1920/1080");
      background-repeat: no-repeat;
      background-size: 100% 100%;
      width: 100vh;
    
    
    .container
     position: relative;
    
    
    .title
    
      font-family: 'Poppins';
    
    
    
    .subtitle
    
      font-family: 'Poppins';
    
    
   <div class="container">
          
          <picture>
            <img
              src="https://picsum.photos/1920/1080"
            />
          </picture>
        </div>
    
        <span style="text-align:center" class="text-block">
    
          <h1 class="title">Hubble Space Telescope</h1>
    
          <h2 class="subtitle">30 Years of Discovery</h2>
    
        </span>

【问题讨论】:

【参考方案1】:

您可以像这样实现文本的居中:(注意:我稍微更改了您的 HTML。)

.container
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  position: relative;

.text-block
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
 <div class="container">
    <picture>
      <img  src="https://picsum.photos/1920/1080"/>
    </picture>
    <span style="text-align:center" class="text-block">
        <h1 class="title">Hubble Space Telescope</h1>
        <h2 class="subtitle">30 Years of Discovery</h2>
    </span>
</div>

【讨论】:

以上是关于如何以响应的方式(不断地)居中文本?的主要内容,如果未能解决你的问题,请参考以下文章

以编程方式在 ImageView 上居中 TextView

如何在具有(流体高度)的响应框中垂直居中文本[重复]

在 Android 的 Textview 中以编程方式居中文本

如何将零宽度元素的文本水平居中?

如何在 XCode 中将标签的文本居中

Swift - 以编程方式居中 UITextView