Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a negative margin equal with the half of the image's width in css?

Tags:

html

css

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?

like image 561
Stefan Avatar asked May 26 '17 17:05

Stefan


People also ask

How do you add negative margins in 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 .

Can we give negative value to margin and padding?

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.

How do you make the margins equal in CSS?

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.

How do you do negative 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.


1 Answers

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">
like image 112
Roko C. Buljan Avatar answered Sep 25 '22 02:09

Roko C. Buljan