使用相对对齐将H1与CSS对齐

时间:2015-05-20 22:18:44

标签: html css

所以我有一个带背景图像的DIV标签:

<a href="#">
  <div class="pagebar jquery">
    <h1>JQuery Demonstrations</h1>
  </div>
</a>

应用的CSS是:

.pagebar {
left: 0%;
right: 0%;
height: 200px;
border:1px solid black;
clear: both;
text-decoration:none;
font-size:x-large;
-webkit-filter: blur(0px);
filter: blur(0px);
margin-top:20px;
}
.pagebar:hover {
border:1px solid black;
-webkit-filter: blur(1px);
filter: blur(1px);
}

我想让文本'JQuery Demonstrations'浮动到背景图像的右侧。但是,当我更改jquery类中的代码时:

.jquery {
background-image: url(file:///C|/Users/James/Desktop/Website/Images/JQuery.jpg);
background-repeat:no-repeat;
background-size: 70% 100%;
background-position:left;
}
.jquery h1 {
width: 40%;
position:relative;
top: 5%;
bottom: auto;
right: auto;
left: 50%;
}

使用'left:auto'和'right:10%'的值,文本会从div的左侧消失。我错过了什么或格式错了吗?我尝试改变宽度,因为之前占用div的整个宽度,但似乎没有变化。

1 个答案:

答案 0 :(得分:0)

h1是一个块元素,默认情况下占用窗口的整个宽度。 position: relative并没有改变它。

因此,通过设置right属性向左推,即使只有10%,也会将其部分推出窗口,是的。 right不仅推动右侧,而是推动整个区块。或者换句话说,right: 10%与相对定位的块上的left: -10%完全相同。

现在,如果您想要的是要在窗口右侧显示的文字,text-align:right就足够了,无需定位。
但是,如果您希望文本完全显示在背景图片的右侧,请将其left:70%width:30%。但请注意,文本相当大,并且不会总是适合窗口宽度的30%,并且会溢出它。

&#13;
&#13;
.pagebar {
  height: 200px;
  border: 1px solid black;
  clear: both;
  text-decoration: none;
  font-size: x-large;
  margin-top: 20px;
}
.pagebar:hover {
  -webkit-filter: blur(1px);
  filter: blur(1px);
}
.jquery {
  background: url('http://lorempixel.com/1000/200') no-repeat;
  background-size: 70% 100%;
  background-position: left;
}
.jquery h1 {
  position: relative;
  left: 70%;
  width: 30%;
}
&#13;
<a href="#">
  <div class="pagebar jquery">
    <h1>JQuery Demonstrations</h1>
  </div>
</a>
&#13;
&#13;
&#13;