Search code examples
htmlcsshyperlinkalignmentcenter

HTML / CSS: How to align link to another website to Center of Webpage --> Tried Align Link to Center in CSS ... did not work


I have the following HTML code with the body tag:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Dwight Schrute's Bidding Blunder</title>

    <!-- the MAIN.CSS file is linked here -->
    <link rel="stylesheet" href="guessing-game.css">


  </head>

  <body>

    <body class='bg' background="dwight_schrute.jpg"></body>


    <h1 align="center">Dwight Schrute's Bidding Blunder</h1>

    <div class="youTubeLink">
      <a href="https://www.youtube.com/watch?v=Vhsng72lC4s">The Office Episode: Bidding Blunder</a>
    </div> 

    <div>
      <p id="p1">BEFORE I GUESS</p>
      <p id="p2">ANYTHING</p>
      <p id="p3">I ASK MYSELF</p>
      <p id="p4">"WOULD AN IDIOT DO THAT?"</p>
      <p id="p5">AND IF THE ANSWER IS YES</p>
      <p id="p6">I DO NOT GUESS THAT</p>
      <br>
      <p id="p7">-Dwight Schrute</p>
    </div>

 </body>

</html>   

I am trying to have the link align to the center of my page. The CSS is linked to my HTML file (works for other stuff).

I tried the following CSS:

.bg {
    background-size:100% 100%;
}

.youTubeLink {
    text-align: center;
}

.youTubeLink>a {
    color: whitesmoke;
}


a:visited {
    text-align: center;
    /* color: #3C1900; */
    color: whitesmoke;
}

But my link is still left aligned (the link is top left of page and underlined):

enter image description here


Solution

  • You are assigning your text-align property to a link element, which is an inline element, therefore its width is only the size of its contents. If you place your link inside a div element and assign the text-align property to that div, then because the div is a block level element, it takes up 100% of the page width, the link will align to the center of the page:

    body {
      background-color: lightblue;
    }
    
    .youTubeLink {
      text-align: center;
    }
    
    .youTubeLink>a {
      color: whitesmoke;
    }
    <div class="youTubeLink">
      <a href="https://www.youtube.com/watch?v=Vhsng72lC4s">The Office Episode: Bidding Blunder</a>
    </div>