I am using an image with height: 100vh;
, so based on the screen's resolution its size changes. I would like to add a negative left margin to it, equal with the half of its width (which depends on the screen resolution). Any solution to do this only with CSS?
Negative margin-left and -right work the same, provided the element has a width. Here we apply margin-left: -10px and margin-right: 10px. First paragraph with margin-left: -10px . Second paragraph with margin-right: -10px .
No. Padding only takes positive values. Negatives are ignored or treated as 0, which would have the same effect: none. Margins can have negative values, as can other position related properties, but not padding.
You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
This is by far the most common use case for negative margins. You give a container a padding so that its contents have some breathing space. However, you want the header to span the entire container, ignoring the padding. Negative margins are the way to go.
If the negative left position is dependant on (half) the element width you can do like:
transform: translateX(-50%);
*{margin:0;}
.halfThere {
vertical-align: top;
height: 100vh;
transition: 0.4s;
transform: translateX(-50%);
}
.halfThere:hover {
transform: translateX(0%);
}
<img class="halfThere" src="//placehold.it/800x600/0bf">
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