sdaau
sdaau

Reputation: 38619

Make anchor tag size to its div content?

Below is a test file, test.htm, which results with this in Firefox:

testhtm

The <div> is green with yellow border and specified size, and the <a> is with red border. Clearly, the anchor tag has both larger width and height that the div that it contains. How can I make the anchor tag equal in size to its div contents - however, in such a way that the size and position of the <div> is unchanged? Basically, for this example and the browser window size shown, I'd want this (manually edited pic):

testhtm2

test.htm:

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style type="text/css">
body {
  padding:0;
  margin:0;
  width: 100%;
  height: 100%;
  background-color: white;
  color: darkred;
}
div#button {
  margin-top: 2vh;
  padding: 2em;
  width: 20em;
  border-style: solid;
  border-width: 2px;
  border-color: yellow;
  background-color: lightgreen;
  text-align: center;
  font-size: 3vh;
  /* to center div horizontally: */
  margin-left: auto;
  margin-right: auto;
}
a {
  text-decoration: none; /*remove underline of a href link:*/
  display: block;
  width: auto;
  padding: 0;
  margin: 0;
  color: unset;
  border-style: solid;
  border-width: 2px;
  border-color: red;
}
  </style>
</head>

<body>
<br/>
<a href="test.zip" target="_blank"><div id="button">Download this</div></a>
</body>
</html>

Upvotes: 2

Views: 5283

Answers (2)

Michael Schmidt
Michael Schmidt

Reputation: 9230

Change the a from display: block; to display: inline-block;.
In order to get the exact same height, remove the margin-top of the div.

In order to keep it centered, add text-align:center to the parent element, in your case your body. Note: in this way, everything inside the body will be centered.
If you only want your a-tag be centered, add a wrapper div around it and add the text-align:center.

Codepen example:
http://codepen.io/anon/pen/jrNvzx

Upvotes: 6

Abhishek Pandey
Abhishek Pandey

Reputation: 13558

Try this:

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style type="text/css">
body {
  padding:0;
  margin:0;
  width: 100%;
  height: 100%;
  background-color: white;
  color: darkred;
}
div#button {
  padding: 2em;
  width: 20em;
  border-style: solid;
  border-width: 2px;
  border-color: yellow;
  background-color: lightgreen;
  text-align: center;
  font-size: 3vh;
  /* to center div horizontally: */
  margin-left: auto;
  margin-right: auto;
}
a {
  text-decoration: none; /*remove underline of a href link:*/
  display:inline-block;
  width: auto;
  padding: 0;
  margin: 0;
  color: unset;
  border-style: solid;
  border-width: 2px;
  border-color: red;
}
  </style>
</head>

<body>
<br/>
<a href="test.zip" target="_blank"><div id="button">Download this</div></a>
</body>
</html>

Upvotes: 1

Related Questions