【问题标题】:Is it possible to center a div with another element that wouldn't affect the centering?是否可以将 div 与另一个不会影响居中的元素居中?
【发布时间】:2017-05-30 08:40:53
【问题描述】:

是否可以在 div 中将 div 居中并在第一个 div 的右侧有一个元素但不影响另一个元素的居中。对于下图,Text1 是否仍位于蓝色 div 的中心,而 Text2 位于右侧?

https://i.stack.imgur.com/1pXav.png

(Text1 相对居中,当文本不多但仍略微偏离中心时。)

【问题讨论】:

    标签: html css position


    【解决方案1】:

    您可以在顶部/右侧元素上使用绝对定位。只需将父元素设为position: relative 并在右侧元素上,您可以使用top: 50%; translateY(-50%); 将其垂直居中。

    div {
      text-align: center;
      position: relative;
      background: black;
      color: white;
    }
    span {
      position: absolute;
      top: 50%; right: 0;
      transform: translateY(-50%);
    }
    <div>
      text
      <span>foo</span>
    </div>
      

    【讨论】:

      【解决方案2】:

      position: absolute;right: 0;top: 0; 一起使用

      margin-top: 100px; 不需要,它只是在顶部增加了一些空间)

      .container {
        margin-top: 100px;
        text-align: center;
        background: aqua;
        height: 100px;
      }
      
      .right-top {
        margin-top: 100px;
        position: absolute;
        right: 0;
        top: 0;
        display: inline-block;
        border: 2px solid red;
      }
      
      body {
        margin: 0;
      }
      <div class="container">TEXT1
        <div class="right-top">TEXT2</div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-06
        • 1970-01-01
        • 2015-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多