sdaau sdaau - 1 month ago 9x
CSS Question

Make anchor tag size to its div content?

Below is a test file,

, which results with this in Firefox:


is green with yellow border and specified size, and the
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
is unchanged? Basically, for this example and the browser window size shown, I'd want this (manually edited pic):



<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style type="text/css">
body {
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;

<a href="" target="_blank"><div id="button">Download this</div></a>


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: