Is it possible to center an image only trough setting a class to the img
tag without side effects? The problem is the following: I have an anchor around an image. If I use the following CSS
.aligncenter {
clear: both;
display: block;
margin-left: auto;
margin-right: auto;
}
And this (stripped down) HTML:
<a href="/path/to/image.jpg" class="fancybox" rel="fancybox" title="System">
<img src="/path/to/image.jpg" title="System" class="aligncenter">
</a>
the link takes the whole width of the main div. This means not only the image is clickable - also the space around the image (actually the whole width) is clickable. This is through the CSS display: block
.
How can I center an image without using a parent div? I don't want the whole area clickable.
Background:
You can read this topic. It is about Wordpress and the built in editor. He automatically generates the class aligncenter
on an image (if the user pressed the center button). I need this for my own theme. According to the moderators there this should be only a CSS question and doesn't have to do with changing code in Wordpress.
HTML | <img> align Attribute. The <img> align attribute is used to set the alignment of an image. It is an inline element. It is used to specify the alignment of the image according to surrounding elements.
Similarly, when we add a link, it is displayed at its default position, but you can center align them using the CSS properties. There are two methods to center the link: Center links in CSS using the “text-align” property. Center links in CSS using the “margin” property.
To center an image with CSS Grid, wrap the image in a container div element and give it a display of grid . Then set the place-items property to center.
in aligncenter class add text-align:center
.aligncenter {
clear: both;
display: block;
margin-left: auto;
margin-right: auto;
text-align:center;
}
I'm not familiar with wordpress, but you might want to try setting the image's and the anchors's css 'display' property to 'inline-block'.
If you are limited in changing the document's DOM, another option is adding an 'onClick' attribute to the image.
This will allow you to run some function once the image is clicked.
So, for example, if you want to redirect to another page:
<img src='myImg.png' onclick='myRedirect()' style='cursor:pointer'/>
And in the page's header:
<script type='text/JavaScript'>
var myRedirect = function(){
window.location.href = 'Some other location';
}
</script>
Notice the style='cursor:pointer'
, which changes the mouse's cursor to a 'hand' cursor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With