定位元素的麻烦

时间:2018-01-08 20:26:15

标签: html css

在我的页面中,我遇到了在标题div之外使用我的元素获得正确位置的问题。我希望它自动定位在不在其中的div之后/之下。

我猜“位置:修复”会破坏文档流程,有什么方法可以解决这个问题,所以我不需要使用它吗?我使用它的原因是因为我想要一个标题背景图像。

我觉得自己真的很愚蠢。

我能得到你的帮助吗?

HTML和CSS代码:

.header {
	left: 0;
	top: 0;
	height: 50%;
	position: fixed;
	right: 0;
	z-index: -1;

}

.pic1 {
	position: absolute;
	width: 100%;
	height: 100%;
	z-index: -1;

}

.menu {
	float: right;
	margin-right: 30px;
	margin-top: 10px;
} 

.font {
	color: gray;
	text-decoration: none;
	font-size: 20px;

h1 {
	color: yellow;
}
<!DOCTYPE html>
<html>
    <head>
		<title>Gesällprov</title>
		<meta charset="UTF-8">
		<link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
		<div class="header">
			<div class="menu">
				<a class="font" style="margin-right:30px" href="">HOME</a>
				<a class="font" style="margin-right:30px" href="">SHOP</a>
				<a class="font" style="margin-right:30px" href="">ABOUT US</a>
				<a class="font" style="margin-right:30px" href="">CONTACT</a>
			</div>	
			<img class="pic1" src="pic1.jpg" alt="fake.jpg">	
		</div>
		<h1>test</h1>
    </body>
</html>

3 个答案:

答案 0 :(得分:2)

元素.header已从自然文档流中删除,因此之前占用的空间不再被占用 - 请将此元素视为不再是兄弟姐妹的一部分或与其交互元素。这就是为什么h1元素似乎是&#34;内部&#34;这个元素实际上是低于它。

要解决此常见问题,您需要考虑此绝对定位元素的空间(height DOM让它仍然是正常文档流程的一部分。

在这个特定的例子中,这个值是动态的;元素的height会有所不同,您还需要使用 relative 长度值(如百分比值)来抵消此空间。

考虑在相应元素上声明marginpadding属性。在这种情况下,更好的选择可能是在padding-top元素上声明body属性,例如:

body {
    padding-top: 25%; /* adjust accordingly to suit requirements */
}

注意:如有必要,请尝试使用@media查询

为各种分辨率相应调整此属性值

代码段示范:

&#13;
&#13;
/* Additional */
body {
    padding-top: 25%; /* adjust accordingly to suit requirements */
}

.header {
  left: 0;
  top: 0;
  height: 50%;
  position: fixed;
  right: 0;
  z-index: -1;
}

.pic1 {
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.menu {
  float: right;
  margin-right: 30px;
  margin-top: 10px;
}

.font {
  color: gray;
  text-decoration: none;
  font-size: 20px;
}

h1 {
  color: black;
}
&#13;
<!DOCTYPE html>
<html>

<head>
  <title>Gesällprov</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <div class="header">
    <div class="menu">
      <a class="font" style="margin-right:30px" href="">HOME</a>
      <a class="font" style="margin-right:30px" href="">SHOP</a>
      <a class="font" style="margin-right:30px" href="">ABOUT US</a>
      <a class="font" style="margin-right:30px" href="">CONTACT</a>
    </div>
    <img class="pic1" src="https://placehold.it/800x225" alt="fake.jpg">
  </div>
  <h1>test</h1>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

.pic1属性top等于标题的高度。

PS:另外,您可以将.pic1属性bottom等于.pic1的负高度。

答案 2 :(得分:-1)

只需使用char

HTML:

margin-top

CSS:

<div class="content">
    <h1>test</h1>
</div>