Include link in a container
I have a container in my code and I need it to be clickable, with href
, let's assume that when clicking it directs to "Google.com". How can I do this?
<div class="project-2 v-center">
<div><!--v-center-->
<div class="container">
<h1>COMPADRE IPSUM</h1>
<p>Eiiitaaa Mainhaaa!! Esse Lorem ipsum é só na brincadeira!!.</p>
</div>
<!--/.container-->
</div>
<!--/v-center-->
A Class:
.container {
position: relative;
z-index: 2;
}
3 answers
The exchange of DIV
for a A
allows the use of the traditional href
, and works even without JS:
CSS:
.container {
display:block;
position: relative;
z-index: 2;
text-decoration:none;
... outras estilizações necessárias ...
}
HTML:
<div class="project-2 v-center">
<div><!--v-center-->
<a class="container" href="http://google.com">
<h1>COMPADRE IPSUM</h1>
<p>Eiiitaaa Mainhaaa!! Esse Lorem ipsum é só na brincadeira!!.</p>
</a>
<!--/.container-->
</div>
<!--/v-center-->
This solution only passes validation in HTML5.
In HTML4, block elements within <A>
were not valid. In practice they worked, but did not pass validation, therefore, a risk of side effects to be avoided.
Further Reading: Block level links and accessibility(en)
this answer is equivalent to the second suggestion of @Guilherme Bernal's answer, which I consider better than the first, and so I elaborated with the relevant details.
For this the simplest way is to use javascript in the onclick event of div
:
<div style="cursor: hand;" onclick="location.href='www.google.com'">
Qualquer coisa aqui
</div>
The problem with this is that it won't behave exactly the same as an ordinary link. You cannot, for example, right-click to copy the url, or middle-click. A slightly better way is instead of trying to make the div behave like a link, is to make the link behave like a div. For this use display: block
:
<a href="www.google.com" style="display: block;">
Qualquer coisa aqui
</a>
I recommend you put the tag inside the title and paragraph tagging tags, getting the code like this:
<div class="project-2 v-center">
<div><!--v-center-->
<div class="container">
<h1><a href="http://www.google.com">COMPADRE IPSUM</a></h1>
<p><a href="http://www.google.com">Eiiitaaa Mainhaaa!! Esse Lorem ipsum é só na brincadeira!!.</a></p>
</div>
<!--/.container-->
</div>
<!--/v-center-->
</div>
This way you pass W3C validation without problems.
If you want to keep the container structure you need to use some Javascript (jQuery) in the case:
<script type="text/javascript">
$(document).ready(function(){
$('.container').click(function(){
window.location="http://seu.site.com/";
});
});
</script>
Don't forget to import the jQuery library.
And in css just add the attribute cursor:poiter
I hope I helped. Good Luck!