【问题标题】:CSS center align DIV keeping text within left aligned?CSS中心对齐DIV将文本保持在左对齐?
【发布时间】:2020-12-19 16:12:21
【问题描述】:

我有以下 DIV 分布:

--------------------       --------------------
| large image here |       | large image here |
--------------------       --------------------

      Text one                   Text two
      here                       here

图像在 DIV 中,文本在 DIV 中。我需要将文本 DIV 与图像 DIV 居中对齐,但文本 DIV 的内容必须保持左对齐。

PS:不能使用固定宽度的 DIV,因为它是一个内容流畅的网站(使用 Bootstrap)。

有什么想法吗?

【问题讨论】:

  • 文本分割的宽度..这取决于什么?文本或视口的长度?

标签: html css alignment


【解决方案1】:

Css Grid 非常灵活,以下代码将为您提供所需的结果。我没有使用引导程序并依赖网格。

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
}

.container > * {
  align-self: center;
  justify-self: center;
}

.container img{
  width: 100px;
  height: 100px;
}
<div class="container">
    <img src="https://gravatar.com/avatar/1c8e8a6e8d1fe52b782b280909abeb38?s=400&d=robohash&r=x" alt="">
    <img src="https://gravatar.com/avatar/1c8e8a6e8d1fe52b782b280909abeb38?s=400&d=robohash&r=x" alt="">
    <div>Some text</div>
    <div>Some text</div>
</div>

【讨论】:

    【解决方案2】:

    Css flexbox grid with text-align: center

    Justify-content: justify-content 属性将伸缩容器的内容对齐在主轴上,默认情况下(在 Web 的情况下)是水平轴。

    CSS 中的 text-align 属性 用于对齐块元素的内部内容。

    img {
        max-width:100%;
    }
    .flex-container {
        display: flex;
        text-align: center;
    }
    .flex-container > div {
        flex:1;
    }
    .text-content {
        text-align: left;
        display:inline-block;
    }
       
    
     <div class="flex-container">
      <div class="flex-item">
        <figure><img src="https://i.imgur.com/HPrl3u8.jpg[/img]"></figure>
        <div class="text-content">Text one <br>
          Here </div>
      </div>
      <div class="flex-item">
        <figure><img src="https://i.imgur.com/HPrl3u8.jpg[/img]"></figure>
        <div class="text-content"> Text two<br>
          Here</div>
      </div>
    </div>

    【讨论】:

    • 正如我所提到的,使用固定宽度是不可接受的,因为它可以在桌面屏幕上工作,但在移动设备上却不行......
    • 请按照逻辑,我更新了现在没有宽度的sn-p。无论有没有宽度,它都可以正常工作。
    • 您的代码在桌面上看起来不错,但在移动设备上却不流畅(它应该在小屏幕上向下推右大图像)。我认为这可能是与 Bootstrap 的某种不兼容。无论如何都不要介意...我只是放弃了居中的文本块以左对齐并且也将其居中...
    • 我当前的代码:

      文本1

      文本 2