I know this question is very popular, but I couldn't find any elegant answer.
I need to align horizontally 2 images and center them. I've already read about inline-block and I pretty good at margins (margin 0 auto trick), paddings and other geometrics. The thing is... that my html code is parsed from markdown by javascript parser (not mine and complex) and each element enclosed into <p> tag. But my text-align for <p> tag is justified.
I understand that answer on my question is to use <div> right in markdown around images and set its text-align to center, but I seek for more elegant way to do it because I prefer clean and modern coding with html5 semantics and look into the future where <div> elements would be no more.
Basically, my question is simple: is it possible at all to do such a thing without outside block?
UPD: jsfiddle - http://jsfiddle.net/8274L7wc/
It'd be perfect if I could change style of <p> based on child element <img>, but as far as I know - this is impossible by css.
Also I suppose I could use CSS calc() method to calculate width and set precise margins, but I think even div would be better than this.
I can't use text-align:center on <p> element because it would make everything centered, not only images.
UPD2:
I've made quick temporary solution by using jquery .parents method to set all <p> which contain <img> tag - centered:
$('img').parents('p').css('text-align', 'center');
Here are a couple of answers that you might find useful.
FIRST
There is a general rule in web development that says you should always try to use basic browsers' functions before relying on CSS. This is part of what we call progressive enhancement. Following this rule, the best way to solve your problem is by adding the html5 element <figure></figure>. Here is the doc and below is an example using your jsfiddle:
p {
text-align: justify;
}
figure { /* Then you can center your img inside the figure element */
text-align: center;
}
img { /* You don't need margin 0 auto or display block, let the browser do its work */
width: 6.25em;
height: 6.25em;
}
<p>
<figure> <!-- You can add several img in a figure element -->
<img src="https://dl.dropboxusercontent.com/u/70091792/Pages/2/workspace2.png" alt="First workspace" title="" />
<img src="https://dl.dropboxusercontent.com/u/70091792/Pages/2/workspace2.png" alt="Web-browser on the second workspace" title="" />
</figure>
</p>
SECOND
If you don't want to add an element to your HTML markup then CSS can only help you if you now how many images you will have and what will be their size. In this case you can calculate with calc() the dimensions needed and add a padding-left on first image. As you can see this is quite complicated, hard to maintain and definitely not considered as best practices. Here is an example:
p {
text-align: justify;
}
img {
width: 100px;
height: 100px;
}
p img:first-child {
margin-left: calc(50% - 100px)
}
<p>
<img src="https://dl.dropboxusercontent.com/u/70091792/Pages/2/workspace2.png" alt="First workspace" title="" />
<img src="https://dl.dropboxusercontent.com/u/70091792/Pages/2/workspace2.png" alt="Web-browser on the second workspace" title="" />
</p>
Good luck!
<p>
<img src="http://leone.ge/mem/img/image2.png" />
<img src="http://leone.ge/mem/img/image2.png" />
</p>
----
p{
display:block;
width:100%;
background:tan;
text-align:center
}
p img{
display:inline-block
}
view result here: http://jsfiddle.net/kr76uu46/2/
Here there are 7 css ways to center horizontally and vertically an element in the middle of a div (or a body). Than you can create a second div and you get your solution.
text-align:center
margin:auto
display:table-cell
position:absolute
translate function
flexbox
calc function
img{
width: 100%;
max-width: 150px; //your width
height: auto;
position: relative;
left: calc(25%);
}
<img id="b" src="http://placehold.it/150x150" alt="Sample Image 6">
<img id="a" src="http://placehold.it/150x150" alt="Sample Image 6">
Otherwise, if you are still interesting looking for different ways (css-based solution) check this LINK
I have many imported SCSS files for third party plugins which could be the problem, but essentially if I directly use the style attribute (inline style) in the div the intended behavior works. But, if I create a class or even an ID it does not apply to it.
Any suggestions on what to look into or immediate corrections would be greatly appreciated.
<div class="box" style="margin-left: 50px; margin-right: 50px">
<div class="padded" >
<%= #step.description %>
</div>
</div>
However, when I change the above code to below, and add class to custom.css.scss - it does not work:
<div class="box description">
<div class="padded" >
<%= #step.description %>
</div>
</div>
.description {
margin-left: 50px;
margin-right: 50px
}
It might be that you need to put the styling within the style element.
<style>
.description {
margin-left: 50px;
margin-right: 50px
}
</style>
And here's some more things you might need to know about the style element:
The style attribute has a type attribute that you might see some websites include. Valid values for this attribute are MIME types. For instance, <style type="text/css">. The w3c specs require browsers to default the value to text/css, so omitting it should be (and, as far as I know, is) fine.
For now, you should only place style elements in the <head> of the document, which is where the specs require them be at the moment.
However, in the near future we will be able to scope stylesheets. Scoped sheets can be placed inline in the document and have a scoped attribute set to true on the element. Read more introductory material on scoping here at the MDN.
I suspect that .description is not specific enough to override any pre-existing CSS rules that specify the margin settings for the .box .padded container div.
You might try something like:
.box.description {
margin-left: 50px;
margin-right: 50px
}
or if the specificity is stubbornly high, try:
<div id="thisbox" class="box description">
<div class="padded" >
<%= #step.description %>
</div>
</div>
and adjust the CSS as follows:
div#thisbox.box.description {
margin-left: 50px;
margin-right: 50px
}
(See demo at: http://jsfiddle.net/audetwebdesign/AvRXT/)
The reason your style rule worked as an inline style is that inline styles have a higher precedence than any CSS rules in external style sheets.
PS
I have assumed that you added your CSS rule to a pre-existing CSS/SCSS style sheet or else coded it correctly as an embedded style using the <style> tag in the <head> section of the document. See post by jmeas
You can set the priority of your CSS high by using !important. For example, I was using material cards and card-image class was overriding my CSS so I set it as important.
.project_7_bg {height:250px !important;
object-fit: cover ;
background-color :#408C54}
I am essentially trying to create a version of the "figure" element (upcoming in HTML5), whereby I have an image with a short description below it.
However, I want to limit the width of this entire element to that of the image, so the text isn't wider than the image (wrapping to multiple lines if necessary).
Basic HTML:
<div class="figure">
<img src="..." alt="..." width="..." height="..." /><br />
A description for the image
</div>
I'm well-versed with CSS but I can't think of any pure CSS solution, without adding a style="width:100px" to the div to match the image width.
Update: After a bit of searching and thinking, the best method seems to be using an inline width on the div. I will keep the width attribute on the image, in case I wish the div to be a bit wider than the image (for example to accomodate a longer caption).
This approach also means I could have two images side-by-side with a caption below. If I have a set of images the same size, I can of course add an extra style to each div.
Thanks to everyone who answered!
This could also be accomplished using 'display: table-caption' for the caption, as follows:
HTML
<div class="wrapper">
<img src="image.jpg" />
<div class="caption">My caption...</div>
</div>
Stylesheet
.wrapper {
display: table;
}
.caption {
display: table-caption;
caption-side: bottom;
}
This block can also be floated left of right of other text. I've tested this in IE8+. Here's a JSBin example: http://jsbin.com/xiyevovelixu/1
For setting the width to match the image automatically you could use
.figure {
display: table;
width: 1px;
}
This makes the div behave like a table (not supported in Internet Explorer). Or you could use a table instead of the div. I don't think there is another way of setting the width automatically.
Edit: The simplest way is to forget about the auto width and set it by hand. If it is really needed you can use JavaScript or a table. In this case the use of a table is not so ugly because you are addressing a limitation of the HTML version. In the case of server-side scripting you could also set the width when generating the page.
Stylesheet
div.figure img,
div.figure div.caption {
width: 100%;
}
div.figure div {
overflow: hidden;
white-space: nowrap;
}
note: to enable wrapping just remove that last css line
HTML
<div class="figure" style="width:150px;">
<img src="logo.png" alt="logo" />
<div class="caption">A description for the image</div>
</div>
I've checked it in Chrome, Firefox and IE7 and it looks good in all three. I realise this has the width on the div and not the img, but at least you only need to set the width in one place. Short of using css-expressions (IE only) I can't see a way of setting the outer divs width to the width of the first child element.
I had the same problem and after reading this decided to use an inline-style on the surrounding element. Seems the better solution over using a table to me.
You can also acheive this using the following solution proposed by Temani Afif in his blog post (All credits to him, I just don't want the solution to be forgotten)
<div class="box">
<img>
<h1>Lorem ipsum dolor ..</h1>
</div>
.box {
display: inline-block;
}
h1 {
width: 0;
min-width: 100%;
}
Make the container inline-block, and makes the h1 (or whatever text tag you use) occupy the space dictated by the sibling element. It's essentially a hack, but it works! No unintended semantic consequences like the table solutions
You could use the display:table solution for all other browsers, and a CSS Behaviour for Internet Explorer.
I have a <div> block with some fancy visual content that I don't want to change. I want to make it a clickable link.
I'm looking for something like <div> … </div>, but that is valid XHTML 1.1.
Came here in the hope of finding a better solution that mine, but I don't like any of the ones on offer here. I think some of you have misunderstood the question. The OP wants to make a div full of content behave like a link. One example of this would be facebook ads - if you look, they're actually proper markup.
For me the no-nos are: javascript (shouldn't be needed just for a link, and very bad SEO/accessibility); invalid HTML.
In essence it's this:
Build your panel using normal CSS techniques and valid HTML.
Somewhere in there put a link that you want to be the default link if the user clicks on the panel (you can have other links too).
Inside that link, put an empty span tag (<span></span>, not <span /> - thanks #Campey)
give the panel position:relative
apply the following CSS to the empty span:
{
position:absolute;
width:100%;
height:100%;
top:0;
left: 0;
z-index: 1;
/* fixes overlap error in IE7/8,
make sure you have an empty gif */
background-image: url('empty.gif');
}
It will now cover the panel, and as it's inside an <A> tag, it's a clickable link
give any other links inside the panel position:relative and a suitable z-index (>1) to bring them in front of the default span link
You can't make the div a link itself, but you can make an <a> tag act as a block, the same behaviour a <div> has.
a {
display: block;
}
You can then set the width and height on it.
This is an ancient question, but I thought I'd answer it since everyone here has some crazy solutions. It's actually very very simple...
An anchor tag works like this -
EVERYTHING IN HERE TURNS INTO A LINK
Sooo...
<div id="thediv" />
Although I'm not sure if this is valid. If that's the reasoning behind spoken solutions, then I apologise...
Requires a little javascript.
But, your div would be clickable.
<div onclick="location.href='http://www.example.com';" style="cursor:pointer;"></div>
This option doesn’t require an empty.gif as in the most upvoted answer:
HTML:
<div class="feature">
</div>
CSS:
div.feature {
position: relative;
}
div.feature a {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
text-decoration: none; /* No underlines on the link */
z-index: 10; /* Places the link above everything else in the div */
background-color: #FFF; /* Fix to make div clickable in IE */
opacity: 0; /* Fix to make div clickable in IE */
filter: alpha(opacity=1); /* Fix to make div clickable in IE */
}
As proposed at http://www.digitalskydesign.com/how-to-make-an-entire-div-a-link-using-css/
This is a "valid" solution to achieving what you want.
<style type="text/css">
.myspan {
display: block;
}
</style>
<span class="myspan">text</span>
But most-likely what you really want is to have an <a> tag displayed as a block level element.
I would not advise using JavaScript to simulate a hyperlink as that defeats the purpose of markup validation, which is ultimately to promote accessibility (publishing well-formed documents following proper semantic rules minimizes the possibility the same document will be interpreted differently by different browsers).
It would be preferable to publish a web page that does not validate, but renders and functions properly on all browsers, including ones with JavaScript disabled. Furthermore, using onclick does not provide the semantic information for a screen reader to determine that the div is functioning as a link.
The cleanest way would be to use jQuery with the data-tags introduced in HTML. With this solution you can create a link on every tag you want. First define the tag (e.g. div) with a data-link tag:
<div data-link="http://www.google.at/">Some content in the div which is arbitrary</div>
Now you can style the div however you want. And you have to create also the style for the "link"-alike behavior:
[data-link] {
cursor: pointer;
}
And at last put this jQuery call to the page:
$(document).ready(function() {
$("[data-link]").click(function() {
window.location.href = $(this).attr("data-link");
return false;
});
});
With this code jQuery applys a click listener to every tag on the page which has a "data-link" attribute and redirects to the URL which is in the data-link attribute.
Not sure if this is valid but it worked for me.
The code :
<div style='position:relative;background-color:#000000;width:600px;height:30px;border:solid;'>
<p style='display:inline;color:#ffffff;float:left;'> Whatever </p>
<a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a>
</div>
To make thepeer's answer work in IE 7 and forward, it needs a few tweaks.
IE will not honour z-index if the element is has no background-color, so the link will not overlap parts of the containig div that has content, only the blank parts. To fix this a background is added with opacity 0.
For some reason IE7 and various compatibility modes completely fail when using the span in a link approach. However if the link itself is given the style it works just fine.
.blockLink
{
position:absolute;
top:0;
left: 0;
width:100%;
height:100%;
z-index: 1;
background-color:#ffffff;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
opacity:0;
}
<div style="position:relative">
<some content>
<a href="somepage" class="blockLink" />
<div>
you could also try by wrapping an anchor, then turning its height and width to be the same with its parent. This works for me perfectly.
<div id="css_ID">
</div>
An option that hasn't been mentioned is using flex. By applying flex: 1 to the a tag, it expands to fit the container.
div {
height: 100px;
width: 100px;
display: flex;
border: 1px solid;
}
a {
flex: 1;
}
<div>
Link
</div>
This worked for me:
HTML:
<div>
WHATEVER YOU WANT
<a href="YOUR LINK HERE">
<span class="span-link"></span>
</a>
</div>
CSS:
.span-link {
position:absolute;
width:100%;
height:100%;
top:0;
left: 0;
z-index: 9999;
}
This adds an invisible element (the span), which covers your entire div, and is above your whole div on the z-index, so when someone clicks on that div, the click is essentially intercepted by your invisible "span" layer, which is linked.
Note: If you're already using z-indexes for other elements, just make sure the value of this z-index is higher than anything you want it to rest "on top" of.
why not? use <div></div> works fine in HTML5
This example worked for me:
<div style="position: relative; width:191px; height:83px;">
</div>
This post is Old I know but I just had to fix the same issue because simply writing a normal link tag with the display set to block does not make the whole div clickable in IE. so to fix this issue far simpler than having to use JQuery.
Firstly let us understand why this happens: IE wont make an empty div clickable it only make the text/image within that div/a tag clickable.
Solution: Fill the div with a bakground image and hide it from the viewer.
How?
You ask good questions, now listen up.
add this backround style to the a tag
> "background:url('some_small_image_path')
> -2000px -2000px no-repeat;"
And there you have it the whole div is now clickable. This was the best way for me cause Im using it for my Photo Gallery to let the user clik on one half of the image to move left/right and then place a small image as well just for visual effects. so for me I used the left and right images as background images anyway!
Just have the link in the block and enhance it with jquery. It degrades 100% gracefully for anyone without javascript. Doing this with html isn't really the best solution imho.
For example:
<div id="div_link">
<h2>The Link and Headline</h2>
<p>Some more stuff and maybe another link.</p>
</div>
Then use jquery to make the block clickable (via web designer wall):
$(document).ready(function(){
$("#div_link").click(function(){
window.location=$(this).find("a").attr("href"); return false;
});
});
Then all you have to do is add cursor styles to the div
#div_link:hover {cursor: pointer;}
For bonus points only apply these styles if javascript is enabled by adding a 'js_enabled' class to the div, or the body, or whatever.
This is the best way to do it as used on the BBC website and the Guardian:
I found the technique here:
http://codepen.io/IschaGast/pen/Qjxpxo
heres the html
<div class="highlight block-link">
<h2>I am an example header</h2>
<p>This entire box links somewhere, thanks to faux block links. I am some example text with a custom link that sits within the block</p>
</div>
heres the CSS
/**
* Block Link
*
* A Faux block-level link. Used for when you need a block-level link with
* clickable areas within it as directly nesting a tags breaks things.
*/
.block-link {
position: relative;
}
.block-link a {
position: relative;
z-index: 1;
}
.block-link .block-link__overlay-link {
position: static;
&:before {
bottom: 0;
content: "";
left: 0;
overflow: hidden;
position: absolute;
right: 0;
top: 0;
white-space: nowrap;
z-index: 0;
}
&:hover,
&:focus {
&:before {
background: rgba(255,255,0, .2);
}
}
}
<div> … </div>
Actually you need to include the JavaScript code at the moment,
check this tutorial to do so.
but there is a tricky way to achieve this using a CSS code
you must nest an anchor tag inside your div tag and you must apply this property to it,
display:block;
when you've done that,it will make the whole width area clickable (but within the height of the anchor tag),if you want to cover the whole div area you must set the height of the anchor tag exactly to the height of the div tag,for example:
height:60px;
this is gonna make the whole area clickable,then you can apply text-indent:-9999px to anchor tag to achieve the goal.
this is really tricky and simple and it's just created using CSS code.
here is an example: http://jsfiddle.net/hbirjand/RG8wW/
This work for me:
<div onclick="location.href='page.html';" style="cursor:pointer;">...</div>
You can give a link to your div by following method:
<div class="boxdiv" onClick="window.location.href='https://www.google.co.in/'">google</div>
<style type="text/css">
.boxdiv {
cursor:pointer;
width:200px;
height:200px;
background-color:#FF0000;
color:#fff;
text-align:center;
font:13px/17px Arial, Helvetica, sans-serif;
}
</style>
You can make surround the element with a href tags or you can use jquery and use
$('').click(function(e){
e.preventDefault();
//DO SOMETHING
});
This is the simplest way.
Say, this is the div block I want to make clickable:
<div class="inner_headL"></div>
So put a href as follows:
<a href="#">
<div class="inner_headL"></div>
</a>
Just consider the div block as a normal html element and enable the usual a href tag.
It works on FF at least.
I pulled in a variable because some values in my link will change depending on what record the user is coming from.
This worked for testing :
<div onclick="location.href='page.html';" style="cursor:pointer;">...</div>
and this works too :
<div onclick="location.href='<%=Webpage%>';" style="cursor:pointer;">...</div>
While I don't recommend doing this under any circumstance, here is some code that makes a DIV into a link (note: this example uses jQuery and certain markup is removed for simplicity):
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("div[href]").click(function () {
window.location = $(this).attr("href");
});
});
</script>
<div href="http://www.google.com">
My Div Link
</div>
If you can use bootstrap, one simple solution is to use bootstrap .stretched-link.
https://getbootstrap.com/docs/4.3/utilities/stretched-link/
Sample Code
<div class="card" style="width: 18rem;">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Card with stretched link</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
Go somewhere
</div>
</div>
Soviut's answer was not sufficient for me. I had to use
a { display: inline-flex; }
to remove baseline artifacts, when using just a img in the a.
Enclosing your div inside an anchor tag <a href></a> works like charm:
<a href="">
<div>anything goes here will turn into a link</div>
</a>
My smarty pants answer:
"Evasive answer to: "How to make block level element a hyperlink and validate in XHTML 1.1"
Just use HTML5 DOCTYPE DTD."
Didn't actually hold true for ie7
onclick="location.href='page.html';"
Works IE7-9, Chrome, Safari, Firefox,
if just everything could be this simple...
#logo {background:url(../global_images/csg-4b15a4b83d966.png) no-repeat top left;background-position:0 -825px;float:left;height:48px;position:relative;width:112px}
#logo a {padding-top:48px; display:block;}
<div id="logo"></div>
just think a little outside the box ;-)