【问题标题】:How to position img element sit bottom of its parent and horizontally centered如何定位img元素位于其父元素的底部并水平居中
【发布时间】:2021-01-10 07:16:37
【问题描述】:

body {
  text-align: center;
  margin: 0;
}

.top_container {
  background-color: #eaf6f6;
  height: 100vh;
  width: auto;
  position: relative;
}

.mountain {
  position: absolute;
  bottom: 0;
  margin-left: auto;
}

.cloud {
  position: absolute;
}

h1 {
  margin-top: 0;
}
<body>
  <div class="top_container">
    <img class="cloud" src="https://via.placeholder.com/150/0000FF/808080/" alt="cloud_picture">
    <h1> TEXT </h1>
    <h2>a <span class="">TEXT</span>TEXT</h2>
    <img class="cloud" src="https://via.placeholder.com/150/FFFF00/000000"
 alt="cloud_picture">
    <img class="mountain" src="https://via.placeholder.com/150/FF0000/FFFFFF" alt="mountain_picture">
  </div>
  <h1>LALALALALA</h>
</body>

大家好,

我想将山脉图像定位在 div 的底部并水平居中。

当我将绝对位置设置为将图像定位到 div 的底部时,文本对齐似乎不起作用。我也尝试left:50%; 使其居中,但这也没有改变。

【问题讨论】:

    标签: css


    【解决方案1】:

    这是一种使用 flex 魔法的更优雅的方式

        .top_container {
          display: flex;
          flex-direction: column;
          align-items: center;
        }
    
        .mountain {
          margin-top: auto;
        }
    

    jsFiddle

    【讨论】:

      【解决方案2】:

      你的代码:

      .mountain{
        position: absolute;
        bottom:0;
        margin-left: auto;
      }
      

      示例工作解决方案:

      .mountain{
        position: absolute;
        bottom:0;
        right: 50%;
        transform: translateX(50%);
      }
      

      这里是示例link

      【讨论】:

        【解决方案3】:

        将父级显示为 flex 并添加 justify-content 规则。

            .top_container{
              display: flex;
              justify-content: center;
              background-color: #eaf6f6;
              height: 100vh;
              width: auto;
              position: relative;
            
            }
        
        

        笔: https://codepen.io/richiegarcia/pen/wvGNWdj

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-12
          • 1970-01-01
          • 1970-01-01
          • 2018-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-11
          相关资源
          最近更新 更多