【问题标题】:Div within div vertical center with position relative? [duplicate]div垂直中心内的div与位置相对? [复制]
【发布时间】:2022-01-11 20:02:52
【问题描述】:

我认为可以将一个 div 在另一个 div 中垂直居中,并将其位置设置为相对?我不喜欢绝对位置,因为它把它放在一切之上。

我在这里缺少什么?可以水平居中也没问题。

.main_container {
  position: relative;
  height: 100vh;
  width: 100vw;
}

.main_container .inner_container {
  position relative;
  height: 90%;
  width: 95%;
  margin: auto;
}
<div class="main_container">
  <div class="inner_container">
    //Some content here, img and text etc.
  </div>
</div>

【问题讨论】:

  • 请提供相应的HTML代码。

标签: css


【解决方案1】:

使用Flexbox代替相对定位:

.main_container {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.main_container .inner_container {
  height: 50%;
  width: 50%;
  outline: 1px dotted black;
}

html, body {
  margin: 0;
  padding: 0;
}
<div class="main_container">
  <div class="inner_container">
    //Some content here, img and text etc.
  </div>
</div>

【讨论】:

  • 啊,当然-谢谢。我觉得很奇怪,虽然我无法在相对位置使用 Margin 居中?
  • 在 flexbox 出现之前,CSS 中的垂直居中是很痛苦的。将auto 用于垂直边距将计算为0 - 有关详细信息,请参阅this answer
  • 最好能帮助我们关闭这个第 100 万份的副本。我很确定你知道很多围绕着中心的问题。
【解决方案2】:

我想对你有帮助

.left, .right,.bottom,.top,.center{position: absolute;}
.display-container {width:400px;height:200px; background-color: grey;position: relative;}
.left{bottom: 0;left:0;}.right{right:0;top: 0;}.bottom{bottom:0;right:0;}.top{top:0;}.center{left:50%;top:50%;transform: translate(-50%,-50%);}
.hover {display:none;transition: all 1s;}
.display-container:hover .hover {display: block; transition: all 1s;}
<div class="display-container">
 <div class="center hover">
  Center
 </div>
  <div class="left hover">
  Left
 </div>
 <div class="right hover">
  Right
 </div>
 <div class="bottom hover">
  Bottom
 </div> 
 <div class="top hover">
  Top
 </div>
</div>

【讨论】:

    猜你喜欢
    • 2018-11-20
    • 2018-01-15
    • 2015-04-18
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    相关资源
    最近更新 更多