html - 为什么我的top是: 50% CSS not working?

标签 html css css-position

我正在做一个练习,虽然我之前已经垂直居中,但在这种情况下,我无法居中。

$( document ).ready(function() {

// Appears the search form input
$("#search").addClass("search-init");
	
}); // $(document).ready
body {
	position: relative;
	height: 100%;
	width: 100%;
}

.search-init {
	height: 5rem;
	width: 5rem;
	border: 2px solid green;
	border-radius: 2.5rem;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
  <div id="search">
  </div>
</body>
</html>

最佳答案

html 元素添加高度:

html { height: 100%; }

它会工作 - body 需要空间来占据,所以给 html 一个 100%,然后 body 可以占据完整的 100% 高度。

关于html - 为什么我的top是: 50% CSS not working?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41502260/

相关文章:

html - 在父 div 之外时子 div 内容不可见

HTML/CSS 背景功能我该怎么做

javascript - 如何在单个 html 中为每个容器定义元标记?

javascript - 呈现最初隐藏的 HTML 元素的正确方法

css - 如何在动画图像上添加文本框?

css - Rails 导航栏颜色没有完全改变 Bootstrap

javascript - 在 iOS Safari 中单击会在您点击的下方的元素上触发 "hover state"

css - 无法将 div 层定位在 html slider 之上

css - 将元素向左移动更多,而不通过调整大小移动元素

css - 左侧固定位置侧边栏 : 50%; moving off the left side on small window sizes