html - 为什么 css "margin-top: calc((100%)/2)"的 h1 元素显示在屏幕底部?

标签 html css

为什么当我输入时我的 h1 没有出现在屏幕中间:

h1 {
    margin-top: calc((100%)/2);
    transition: color 0.5s linear, transform 0.5s ease-in-out;
}

(说到margin-top属性)

相反,它显示在屏幕底部,有人可以解释一下原因吗?

最佳答案

margin 百分比为 always based on width .

flexbox

使用flexbox可以达到想要的效果,如下图。

/* Remember that containers' heights are a percentage of their parents' heights */

html, body {
  padding: 0;
  margin: 0;
  height: 100%;
}

.container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

h1 {
  flex: 0 0 auto;
  vertical-align: middle;
}
<div class="container">
  <h1>Hello World</h1>  
</div>

备选

Flexbox 支持非常复杂的场景,但对于这种特殊情况有一种更简单的方法,即使用 vh(视口(viewport)高度)单位。

h1 {
  font-size: 24px;
  line-height: 32px;
  margin-top: calc(50vh - 16px);
}
<h1>Hello World</h1>

附加说明

我不确定你为什么在你的例子中使用 calc(),但如果你这样做,一定要输入 spaces around the operators .除法运算符不需要空格,但进入是个好习惯。

关于html - 为什么 css "margin-top: calc((100%)/2)"的 h1 元素显示在屏幕底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51119715/

相关文章:

html - 100% 宽度的 div,带有显示水平滚动条的填充

php - 如何检查复选框是否返回值?错误 :"Notice: Undefined index:"

javascript - 使用 2D 渲染上下文的 HTML5 Canvas 转换问题

javascript - 如何在弧的末尾添加文字

html - 并排链接在悬停时增加了尺寸,而不会扰乱其他链接

html - Nodejs 提供的 HTML 页面中静态资源的链接不起作用

html - 我不断在CSS中收到此错误,但我不知道为什么

javascript - Bootstrap Carousel 在加载时将图像切成两半

javascript - 如何创建一个带有固定标题的 HTML 表格,该表格可在 IE for windows mobile 等手机中使用?

html - 1 :1 aspect column, 其他收缩/增长