【问题标题】:Div centered on desktop, not on mobile deviceDiv 以桌面为中心,而不是在移动设备上
【发布时间】:2018-07-21 03:53:25
【问题描述】:

当在另一个 div 中居中时,我在桌面上成功了,我尝试在 chrome 的内置“检查”分辨率更改中,但在“移动”上,div 保持在另一个 div 的底部。谁能帮忙,看看为什么 div 以“桌面模式”为中心,而不是以“移动模式”为中心?谢谢

.headercontainer {
  overflow-y: hidden;
}

.header-title {
  width: 80%;
  height: 100px;
  left: 50%;
  top: 50%;
  font-size: 2em;
  z-index: -1;
  position: fixed;
  margin-left: -40%;
  margin-top: -50px;
  height: 100px;
  transform: translateY(-50%);
}

.header-title h1 {
  color: white;
  text-shadow: 2px 2px 4px #d1d1d1;
  font-family: 'Raleway', sans-serif;
  white-space: nowrap;
  text-transform: uppercase;
  text-align: center;
}

.header-image {
    background-image: url("images/Westminster.jpg");
    background-position: center center;
    max-width: 100%;
    margin-left: auto;
    margin-right: auto;
    padding: 5em;
    height:60vh;
    background-size: cover;
    background-attachment: fixed;
    background-repeat: no-repeat;
    position:relative;
    z-index: -3;
}
<div class = "headercontainer">
  <div class = "header-image">
    <div class = "header-title">
      <h1> Anarchists and Autocrats </h1>
    </div>
  </div>
</div>

【问题讨论】:

  • 你应该使用 flex 来居中。
  • 您可能需要同时为headbody.headercontainer 设置height: 100%

标签: html css


【解决方案1】:

您应该使用position:absolute 而不是position:fixed。 通过我的JSFiddle链接或尝试下面的书面代码:

HTML 代码 -

<div class="headercontainer">
    <div class="header-image">
        <div class="header-title">
            <h1> Anarchists and Autocrats </h1>
        </div>
    </div>
</div>

CSS 代码 -

.headercontainer {
    overflow-y: hidden;
    position: relative;
}

.header-title {
    width: 80%;
    height: 100px;
    top: 50%;
    font-size: 2em;
    z-index: -1;
    position: absolute;
    height: 100px;
    transform: translateY(-50%);
}

.header-title h1 {
    color: #404040;
    text-shadow: 2px 2px 4px #d1d1d1;
    font-family: 'Raleway', sans-serif;
    text-transform: uppercase;
    text-align: center;
}

.header-image {
    background: url("https://www.nyhabitat.com/blog/wp-content/uploads/2013/10/westminster-london-houses-parliament-big-ben-thames-river.jpg") center/ cover;
    max-width: 100%;
    margin-left: auto;
    margin-right: auto;
    padding: 5em;
    height: 60vh;
    background-size: cover;
    background-attachment: fixed;
    background-repeat: no-repeat;
    position: relative;
    z-index: -3;
}

【讨论】:

  • 与其给他代码,不如让未来的用户解释原始代码的错误之处会更有信息
  • 我已经更新了我的代码。 @pandavenger。我还提供了解决方案,以便用户可以看到它正在运行。
  • 你好。这行得通,但我确实需要文本不要移动,并被修复。有没有办法做到这一点,或者这是不可能的?
  • 尝试使用 CSS 中的 media 查询根据屏幕大小维护文本的 font-size。 @SimplySnap
  • 你知道我会怎么做吗?很抱歉打扰了
猜你喜欢
  • 2015-07-15
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
相关资源
最近更新 更多