如何在我的网页上将CSS中的文本/链接居中? (有文本对齐问题)

时间:2016-06-24 19:33:46

标签: css

我似乎无法在我的网页上获得指向中心的链接。理论上,下面的代码应该使链接出现在中心,但它不会:

#navigate2 {
  padding: 10px 20px;
  background-color: #555555;
  color: white;
  text-decoration: none;
  border-radius: 4px 4px 0 0;
  text-align: center;
  /*I have included text align but it doesn't seem to be working*/
}

#navigate2:hover {
  background-color: #777777;
  text-decoration: underline;
}
<div class="photo" >
  <h3>Photo &amp; Video</h3>
  <!-- photo goes here -->
  <br> <!-- I want the links labelled navigate 2 to be centered-->
  <a id="navigate2" href="#">Browse my albums!</a>
  <br> <br> <hr>
</div>

<div class="blog">
  <h3>Blog</h3>
  <br> <!-- read above -->
  <a id="navigate2" href="#">Read my blog!</a>
  <br> <br> <hr>
</div>

3 个答案:

答案 0 :(得分:1)

a标记是内联的,因此将文本居中放置无效。您可以尝试添加display: block,或者display: inline-block;margin: 0 auto来集中内联块。

答案 1 :(得分:0)

首先,id应该是唯一的,而是为您的链接提供一个类。其次,a元素是内联的,这意味着您不能将块级样式应用于它。而是在CSS中指定将其显示为块:display:block;

答案 2 :(得分:0)

您需要将text-align:center属性设置为锚标记的父级。不是锚标签

 #navigate2 {
   padding: 10px 20px;
   background-color: #555555;
   color: white;
   text-decoration: none;
   border-radius: 4px 4px 0 0;
   text-align: center;
   /*I have included text align but it doesn't seem to be working*/
 }
 #navigate2:hover {
   background-color: #777777;
   text-decoration: underline;
 }
 .navigate-wrapper {
   text-align: center;
 }
<div class="photo">
  <h3>Photo &amp; Video</h3>
  <!-- photo goes here -->
  <br>
  <!-- I want the links labelled navigate 2 to be centered-->
  <div class='navigate-wrapper'>
    <a id="navigate2" href="#">Browse my albums!</a>
  </div>
  <br>
  <br>
  <hr>
</div>

<div class="blog">
  <h3>Blog</h3>
  <br>
  <!-- read above -->
  <div class='navigate-wrapper'>
    <a id="navigate2" href="#">Read my blog!</a>
  </div>
  <br>
  <br>
  <hr>
</div>