Johan Sundman Johan Sundman - 1 month ago 6
CSS Question

Html <a> tag stretching to entire page width

I just made a nice little button

<div>
wrapped in a link tag
<a>
. The problem is that the
a
tag stretches to the whole width of the page. I have no idea of how and why this happend since it haven't occoured for me before. I'll leave a codepen link and a snippet down here. Thanks in advance guys!
PS Note that the icons are just placeholders for the real ones! Don't judge them!

http://codepen.io/JohanSundman/pen/kkxbLg



/*
.archive-link {
width: 120px;/* Same as the button width *//*
display: block;
}
*/

.archive-button {
position: relative;
margin-left: auto;
margin-right: auto;

width: 120px;
height: 40px;
transition: all 200ms ease-in-out;
}

.archive-button::after {
content: "";
display: inline-block;
width: 15px;
height: 100%;
background-color: #ae3535;
/* Stacking context */
position: absolute;
z-index: -1;
/*Transition*/
transition: width 250ms;
}

.archive-button:hover::after {
width: 100%;
}

.archive-button-down {
background-image: url('https://image.freepik.com/free-icon/arrow-down-angle_318-52905.jpg');
background-size: auto 100%;
background-position: center;
background-repeat: no-repeat;
}

.archive-button-up {
background-image: url('https://image.freepik.com/free-icon/ascendant-chevron-arrow-up_318-28667.jpg');
background-size: auto 100%;
background-position: center;
background-repeat: no-repeat;
}

.archive-button:hover {
background-position: center;
}

<a href="http://www.swiftpeak.net/">
<div class="archive-button archive-button-down"></div>
</a>


<br><br>

<a href="http://www.swiftpeak.net/">
<div class="archive-button archive-button-up"></div>
</a>




Answer

The <a> tag is an inline element, and a <div> tag is a block level element.

Block level elements expand to the width of their parent elements. In this case, it's the <div> that's forcing your <a> to be full width. You could amend the .archive-button class below with a display: inline-block; to alleviate the full-width behaviour you were seeing!

From [MDN][1]:

Block-level vs. inline

There are a couple of key differences between block-level elements and inline elements:

Formatting

By default, block-level elements begin on new lines, but inline elements can start anywhere in a line.

Content model

Generally, block-level elements may contain inline elements and other block-level elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.

Edit: Alternatively, you could also do away with the internal <div> element, and apply .archive-button to your <a> tag directly. Then you'd avoid all the comments about the illegality of a <div> in an <a> tag.

Comments