Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my hyperlinked div stretch across the entire page?

Tags:

html

css

This div is inside a 'page-container' div with a 'content div inside it, but the issue can be reproduced without those (as seen in the Fiddle below).

HTML:

<a href="http://www.example.com"><div class="download_link">Download PDF</div></a>

CSS:

.download_link {
    margin: 0 auto;
    width: 200px;
    border-radius: 5px;
    transition: 0.5s;
    background-color: lightblue;
    text-align: center;
    font-family: 'Source Serif Pro';
    font-weight: 600;
    font-size: 25px;
}

.download_link:hover {
    transition: 0.5s;
    background-color: limegreen;
}

The div links properly and even changes color on hover. But the link stretches across the entire container. I have tried changing the width of all sorts of things.

>>> Convenient JSFiddle <<<

like image 821
Antrikshy Avatar asked Dec 19 '22 13:12

Antrikshy


1 Answers

Generic division (div), by default, is a block element. Blocks, regardless of their width, take an entire line to themselves within their parent. In your case, the parent of the div is an anchor tag, which, by default, is inline. Inlines, likes absolute elements, inline-blocks, and floats, shrink-wrap around their children. The block within an inline inherently wants to "have" a line to itself, which is why it makes its parent stretch to the right and left edges of its body parent.

Franky, placing a div inside an anchor makes little sense. All you really need is just an anchor tag that serves its purpose. And, interestingly, if you display an anchor as a block, then the clickable link area will only be the width of the anchor. You have less markup and the functionality that you want.

Here's the jsfiddle: http://jsfiddle.net/hhm46/2/.

Here's HTML:

<a href="http://www.example.com/manual.pdf">Download PDF</a>
<p>Sample paragraph</p>

Here's CSS:

a[href $= ".pdf"] {
    display: block;
    margin: 0 auto;
    width: 200px;
    border-radius: 5px;
    transition: background-color 0.5s;
    background-color: lightblue;
    text-align: center;
    font-family: 'Source Serif Pro';
    font-weight: 600;
    font-size: 25px;
}

a[href $= ".pdf"]:hover {
    transition: 0.5s;
    background-color: limegreen;
}
like image 84
DRD Avatar answered Mar 05 '23 20:03

DRD