How can I resize and reposition the image inside a box, in such way that it covers the entire box, similar to how background-size: cover works.
<div class="box" style="width: 100px; height: 100px;">
<img src="pic.jpg" width="413" height="325">
</div>
I know I have to add overflow:hidden to the box and the image needs position: absolute. But what's the formula that gets me the right new size for the image, and left + top positions?
For what it's worth: this can now be done with CSS alone with...
The new CSS property object-fit (Current browser support)
Just set object-fit: cover; on the img
You don't even need to wrap the img in a div!
FIDDLE
img {
width: 100px;
height: 100px;
}
.object-fit {
display: block;
object-fit: cover;
}
.original {
width: auto;
height: auto;
display: block;
}
<img src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Img 'squashed' - not good</p>
<img class="object-fit" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>object-fit: cover -
The whole image is scaled down or expanded till it fills the box completely, the aspect ratio is maintained. This normally results in only part of the image being visible. </p>
<img class="original" src="http://lorempixel.com/413/325/food" width="413" height="325">
<p>Original ing</p>
You can read more about this new property in this webplatform article.
Also, here is a fiddle from the above article which demonstrates all the values of the object-fit property.
Close enough, pure CSS solution for background size cover simulation using img tag with very good browser support (IE8+):
.container {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: hidden;
}
.container img {
position: absolute;
top: 50%;
left: 50%;
width: auto;
height: auto;
max-height: none;
max-width: none;
min-height: 100%;
min-width: 100%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
<div class="container">
<img src="//lorempixel.com/400/200/sports/1/" />
</div>
this may be easier
jQuery
$('.box').each(function() {
//set size
var th = $(this).height(),//box height
tw = $(this).width(),//box width
im = $(this).children('img'),//image
ih = im.height(),//inital image height
iw = im.width();//initial image width
if (ih>iw) {//if portrait
im.addClass('ww').removeClass('wh');//set width 100%
} else {//if landscape
im.addClass('wh').removeClass('ww');//set height 100%
}
//set offset
var nh = im.height(),//new image height
nw = im.width(),//new image width
hd = (nh-th)/2,//half dif img/box height
wd = (nw-tw)/2;//half dif img/box width
if (nh<nw) {//if portrait
im.css({marginLeft: '-'+wd+'px', marginTop: 0});//offset left
} else {//if landscape
im.css({marginTop: '-'+hd+'px', marginLeft: 0});//offset top
}
});
css
.box{height:100px;width:100px;overflow:hidden}
.wh{height:100%!important}
.ww{width:100%!important}
This should handle any size/orientation, and will not only resize, but offset the images. All without relative or absolute positioning.
made a fiddle: http://jsfiddle.net/filever10/W8aLN/
Also for what it's worth, the same effect can be produced by instead of setting "width" and "height" (setting them could break this approach btw):
min-width: 100%;
min-height: 100%;
or
min-width: (your desired percent of viewport width)vw;
min-height: (your desired percent of viewport height)vh;
with
overflow: hidden;
on the parent
:)
The idea is to make additional wrapper for image:
<div class="wrap">
<div class="inner">
<img src="http://placehold.it/350x150">
</div>
</div>
And use such CSS:
.wrap {
position: relative;
width: 100%;
height: 200px;
background: rgba(255, 0, 0, 0.3);
overflow: hidden;
}
.inner {
position: absolute;
min-width: 100%;
height: 100%;
left: 50%;
-moz-transform: translateX(-50%);
-o-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
.inner img {
position: absolute;
min-height: 100%;
min-width: 100%;
top: 50%;
left: 50%;
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
This is working example: https://jsfiddle.net/kr60jroe/
From https://developer.mozilla.org/en-US/docs/Web/CSS/background-size:
cover
This keyword specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.
So, you're either looking at making the width: 100% or the height: 100%, whichever will create an overlap within the parent div. So we can use the following logic:
var makeBackgroundCover = function (div) {
$(div + " img").css("height", "100%");
if ($(div + " img").width() < $(div).width()) {
$(div + " img").css({
"height": "auto",
"width": "100%"
});
}
}
The following fiddle shows this function working on both a horizontal and vertical image.
http://jsfiddle.net/2r5Cb/
Here is my approach:
//collect the nodes
var parent = $('.box');
var img = $('image', box);
//remove width and height attributes
img.removeAttr('width');
img.removeAttr('height');
//set initial width
img.attr('width', parent.width());
//if it's not enough, increase the width according to the height difference
if (img.height() < parent.height()) {
img.css('width', img.width() * parent.height() / img.height());
}
//position the image in the center
img.css({
left: parseInt((img.width() - parent.width())/-2) + 'px',
top: parseInt((img.height() - parent.height())/-2) + 'px'
});
FIDDLE
Here's a clean JavaScript function to do this and an example of implementation:
function backgroundCover(elementSizes, containerSizes) {
var elementRatio = elementSizes.width / elementSizes.height,
containerRatio = containerSizes.width / containerSizes.height;
width = null,
height = null;
if (containerRatio > elementRatio) {
width = Math.ceil( containerSizes.width );
height = Math.ceil( containerSizes.width / elementRatio );
} else {
width = Math.ceil( containerSizes.height * elementRatio );
height = Math.ceil( containerSizes.height );
}
return { width, height };
}
Here's an example of implementation:
HTML
<!-- Make sure the img has width and height attributes. The original image's width and height need to be set in order to calculate the scale ratio. -->
<div class="photo"><img src="photo.jpg" width="400" height="300"></div>
CSS
.photo {
position: relative;
overflow: hidden;
width: 200px;
padding-bottom: 75%; /* CSS technique to give this element a 4:3 ratio. */
}
.photo img {
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
JavaScript
$( window ).on( 'resize', function() {
$( '.cover-photo' ).each( function() {
var img = $( 'img', this ),
imgWidth = img.attr( 'width' ),
imgHeight = img.attr( 'height' ),
containerWidth = $( this ).width(),
containerHeight = $( this ).height(),
newSizes = backgroundCover( { width: imgWidth, height: imgHeight }, { width: containerWidth, height: containerHeight } );
img.css( {
width: newSizes.width,
height: newSizes.height
} );
} );
} );
While reading the accepted answer, it strikes me that we simply test on whether the image is 'portrait' or 'landscape':
if (ih>iw) {//if portrait
In the case of the OP, that's right. But others might be dealing with rectangles and should take the aspect ratio of the container and the 'child'-image into consideration:
var int_container_width = parseInt( $_container.width() );
var int_container_height = parseInt( $_container.height() );
var num_container_aspect = int_container_width/int_container_height;
var int_image_width = parseInt( $_image.width() );
var int_image_height = parseInt( $_image.height());
var num_image_aspect = int_image_width/int_image_height;
if ( num_image_aspect > num_container_aspect){
num_scale = int_container_width/int_image_width * 100;
} else {
num_scale = int_container_height/int_image_height * 100;
}
This is a pure css solution. You can define a wrapper with:
div.cover {
position: fixed;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
}
and the img:
img.cover {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
min-width: 50%;
min-height: 50%;
overflow-x: hidden;
}
Here the live example:
http://codepen.io/ErwanHesry/pen/JcvCw
You can use this style to the image tag :"object-fit:cover;"
This link will support you also https://css-tricks.com/almanac/properties/o/object-fit/
If you want the image centered in the box without resizing the image, just use this code:
.box {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
}
.box img {
width: 413px;
height: 325px;
position: absolute;
left: 50%;
top: 50%;
}
If you are looking to resize the image to fit, use the following code:
.box {
width: 100px;
height: 100px;
}
.box img {
width: 100%;
height: auto;
}
This code will leave some white space if the image is wider than it is tall. If neither of these work, you could just set the image as a background and use background-size: cover;.
For anyone who happens across this answer as I did today looking for a solution that will work with landscape, portrait, rectangle, square, etc images and arbitrary container sizes, I have included my own code below.
This will also work responsively, you'll just need to run it again whenever the window resizes.
JSFiddle:
http://jsfiddle.net/66c43ao1/
HTML
<div class="test">
<div class="cover">
<img src="http://d2ws0xxnnorfdo.cloudfront.net/character/meme/cool-dog.jpg" width="590" height="590"/>
</div>
</div>
CSS
/* modify the width and height below to demonstrate coverage */
.test {
height: 300px;
position: relative;
width: 500px;
}
/* you will need the below styles */
.cover {
height: 100%;
left: 0;
overflow: hidden;
position: absolute;
top: 0;
width: 100%;
z-index: 1;
}
JS
$('.cover').each(function() {
var containerHeight = $(this).height(),
containerWidth = $(this).width(),
image = $(this).children('img'),
imageHeight = image.attr('height'),
imageWidth = image.attr('width'),
newHeight = imageHeight,
newWidth = imageWidth;
if (imageWidth < containerWidth) {
// if the image isn't wide enough to cover the space, scale the width
newWidth = containerWidth;
newHeight = imageHeight * newWidth/imageWidth;
}
if (imageHeight < containerHeight) {
// if the image isn't tall enough to cover the space, scale the height
newHeight = containerHeight;
newWidth = imageWidth * newHeight/imageHeight;
}
var marginLeft = (newWidth - containerWidth)/2;
var marginTop = (newHeight - containerHeight)/2;
image.css({
marginLeft : '-' + marginLeft + 'px',
marginTop : '-' + marginTop + 'px',
height : newHeight,
width : newWidth
});
});
You can of course use libraries such as Backstretch which do this same thing, but I found this solution to be better for my purposes (no increase in dependencies, lighter weight, etc).
I created a function below that should do it. I borrowed some of the logic from the accepted answer and adjusted it to work with any container by creating a ratio for image dimension : container dimension and then compared which is greater to figure which dimension to adjust. Also added a 'center' argument ('true' centers, false sets it to top/left).
I'm using CSS3 with the translateX/Y, but could get it working without it easily enough.
Here's the code:
var coverImage = function(wrap, center) {
if (typeof center === 'undefined') {
center = true;
}
var wr = $(wrap),
wrw = wr.width(),
wrh = wr.height();
var im = wr.children('img'),
imw = im.width(),
imh = im.height();
var wratio = wrw / imw;
var hratio = wrh / imh;
//Set required CSS
wr.css({'overflow' : 'hidden'});
im.css({'position' : 'relative'});
if (wratio > hratio) {
im.width(wrw);
im.css({'height' : 'auto'});
if (center) {
im.css({
'top' : '50%',
'transform' : 'translateY(-50%)'
});
}
} else {
im.height(wrh);
im.css({'width' : 'auto'});
if (center) {
im.css({
'left' : '50%',
'transform' : 'translateX(-50%)'
});
}
}
}
and checkout the jsfiddle to see it in action: https://jsfiddle.net/cameronolivier/57nLjoyq/2/
I made something could work to emulate a background-size:cover and background-position:center.
If you want to change the position just change the styles "top" an "left" of the img
CSS
.box{
overflow:hidden;
position:relative;
}
.box img{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
}
JS
$('.box').each(function() {
//aspect ratio of container
var boxRatio = $(this).height() / $(this).width();
//aspect ration of image
var imageRatio = $(this).children('img').height() / $(this).children('img').width();
//set width or height 100% depend of difference
if (imageRatio > boxRatio) {
$(this).children('img').css({"width":"100%","height":"auto"});
} else {
$(this).children('img').css({"height":"100%","width":"auto" });
}
});
This function should be activated on "load" and "resize" event.
Related
I want to set a scale and a margin of an element to make it centered in a fluid way by using wheel event.
I want to use margins for centering as at some point I would like to set scroll position on wrapping element in fluid way as well.
As you can see in jsfiddle example I'm using css transition attribute to make it fluid.
At the same time I'm changing a scale and a margin but it looks like margin animation kicks in faster leading to moving the div side ways first. You can try it with greater zoom and do mousewheel up and down.
How to fix it so it starts and ends simultanously so the cross located in the middle of the picture doesn't move sideways during zooming in and out?
jsfiddle
<html>
<div id="wrap">
<div id="el">
+
</div>
</div>
</html>
var scale = 1;
var $wrap = $('#wrap');
var $el = $('#el');
$(function() {
$el.on('wheel', function (e) {
scale = e.originalEvent.wheelDelta > 0 ? scale * 1.5: scale / 1.5;
e.preventDefault();
var l = ($wrap.width() - $el.width() * scale) / 2;
var t = ($wrap.height() - $el.height() * scale) / 2;
$el.css({
'transform': "scale(" + scale + ")",
'margin-top': t + "px",
'margin-left': l + "px",
});
});
});
#wrap {
position: fixed;
width: 400px;
height: 300px;
background: pink;
}
#el {
position: relative;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
transition: 1s;
transform-origin: 0 0;
background-image: radial-gradient(circle at 0px 0px, #666 1px, transparent 0);
background-size: 4px 4px;
}
Edit: The best way to see the issue is to use mouse scroll once (one tick) and at the end of animation scroll it once again.
Edit2: So I've used Gabriele Petrioli answer and it looks good, however I still needs this info about position of the element. I came up with solution where I 'move'd margins to css transform attribute as 'translate' option and it looks working ok
I've replaced:
$el.css({
'transform': "scale(" + scale + ")",
'margin-top': t + "px",
'margin-left': l + "px",
});
with:
$el.css({
'transform': "translate(" + t + "px, " + l + "px) scale(" + scale + ")",
});
jsfiddle
I would use absolute positioning and position it at the center from the start.
Some changes
use position:absolute and left/right to position it in the center
use transform: translate(-50%, -50%) to match the grid center with the wrapper center
set the origin to 50% 50% as well so you do not have to account for movement
now that you do not need the margins, you can just adjust the scale
added a Math.max/Math.min in there just to keep the example sane for testing.
var scale = 1;
var $wrap = $('#wrap');
var $el = $('#el');
$(function() {
$el.on('wheel', function(e) {
e.preventDefault();
scale = e.originalEvent.wheelDelta > 0 ? scale * 1.5 : scale / 1.5;
scale = Math.min(Math.max(scale, 0.2) ,20);
$el.css({
'transform': `translate(-50%,-50%) scale(${Math.max(scale,0.1)})`,
});
});
});
#wrap {
position: fixed;
width: 400px;
height: 300px;
background: pink;
}
#el {
position: absolute;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
transition: transform 1s;
transform-origin: 50% 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-image: radial-gradient(circle at 0px 0px, #666 1px, transparent 0);
background-size: 4px 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div id="wrap">
<div id="el">
+
</div>
</div>
</html>
I am trying to achieve the following effect: https://github.com/thispagedoesntexist (the one that the character has)
I want my image to move just slightly according to where I move my mouse. Maybe it has something to do with 3d transformation and scaling ... I don't know
I browsed the web and tried to come up with something by myself, but I couldn't. Here's where I stpoped:
HTML
<img class="image" id="module-hotjar" src="./img/image.png" alt="">
CSS
.image{
position: fixed;
z-index: 1;
display: flex;
bottom: -300px;
height: 90vh;
left: 15%;
transition: 0.3s ease;
transform: translate(0px, 0px);
}
JS
var image = document.querySelector('.image');
let root = document.documentElement;
root.addEventListener('mousemove', (e) => {
;
x = e.offsetX / 10;
y = e.offsetY / 10;
image.style.transform = `translate(${x}px,${y}px)`;
});
Thank you
You're on the right track. To achieve this parallax effect, you can apply different ratios to the elements. The difficult part is finding/creating the right images and finding the correct ratios, so that it looks kind of "realistic":
const background = document.querySelector('.background'),
patrick = document.querySelector('.patrick'),
bob = document.querySelector('.bob'),
root = document.documentElement;
root.addEventListener('mousemove', (e) => {
const x = e.clientX,
y = e.clientY;
background.style.transform = `translate(${-x / 20}px,${-y / 40}px)`;
patrick.style.transform = `translate(${-x / 15}px,${-y / 40}px)`;
bob.style.transform = `translate(${x / 10}px,${y / 10}px)`;
});
.background{
position: fixed;
bottom: -5vh;
width: 110vw;
left: -5vw;
}
.patrick{
position: fixed;
bottom: -7vh;
height: 90vh;
right: 10%;
margin-left: -25%;
}
.bob{
position: fixed;
bottom: -10vh;
height: 90vh;
left: 50%;
margin-left: -25%;
}
<img class="background" src="https://wallpaperaccess.com/full/3896911.jpg" />
<img class="patrick" src="https://assets.stickpng.com/thumbs/5cb78e9b7ff3656569c8cec1.png" />
<img class="bob" src="https://lh3.googleusercontent.com/proxy/wHCNlCMGLIi4Fa3QQlxyLRw_uyZoLauUFpMCDzSowxbjmA6gy12KqK6Fe6XD45T6EWas1dimdsh7Rfl3Mv9w3Z28iJAKCqaQLu8TChGV8yzbRqL7WpwHozSPaDYBJIefwmayIaROJ7M" />
I'm using this code to generate some endless running banner:
<style>
#myimage {
position: fixed;
left: 0%;
width: 100%;
bottom: 0%;
background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bildschirm-senkrechter-strich.jpg") repeat-x scroll 0% 0% / contain;
}
</style>
<div id="myimage">.</div>
<script>
var offset = 0
setInterval(function() {
offset +=1
document.getElementById("myimage").style.backgroundPosition = offset + 'px 0px';
},50)
</script>
To my question: Now I'd like every single image to have a size of 100% of the screen.
I thought about just adding the attribute ...
background-size: 100%;
... but it doesn't seems working that way.
How can I set the width of every single image to 100% of the screens width without removing my style attributes?
Increase the height of the div and respect the proportion of the image:
var offset = 0
setInterval(function() {
offset +=1
document.getElementById("myimage").style.backgroundPosition = offset + 'px 0px';
},50)
#myimage {
position: fixed;
left: 0%;
width: 100%;
bottom: 0%;
background:url("http://static.giga.de/wp-content/uploads/2014/08/tastatur-bildschirm-senkrechter-strich.jpg") repeat-x scroll 0% 0% / contain;
/* you image is 1000x433 so we need 43.3% of width*/
padding-bottom:43.3%;
background-size:cover;
}
<div id="myimage"></div>
I have a div that is centered on the page and scales with viewport in a way that its aspect ratio (16:9) is maintained. The problem is, I want the font and content inside to scale with the div as it resizes, as well. Vmin works, for the most part, without issue. It would work perfectly if the aspect ratio of the div is 1:1 because vmin checks for the lesser value between height and width of the viewport directly, and you can't set a custom aspect ratio.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color:white;
}
.wrapper {
width: 95vw;
height: calc(95vw * 9/16);
max-height: 95vh;
max-width: calc(95vh * 16/9);
background: center;
background-color: blue;
background-size:contain;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
#lorem {
color: aqua;
font-size:10vmin;
text-align:center;
position:absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
margin:auto;
}
</style>
</head>
<body>
<div class="wrapper">
<p id="lorem">
This text should scale with div only.
</p>
</div>
</body>
</html>
https://jsfiddle.net/Addictorator/70fq44sv/2/
Resize the window vertically to see what I'm talking about.
I don't believe there is a way in pure css (but if there is, that would be most preferred), but I think it is possible in javascript using an event listener onresize of the div and scaling each element down separately by a ratio comparing original (or previous - storing it as a var) div height/width to current div height/width. Or it could try and replicate vmin behavior but with height set to a ratio in a way 16:9 is considered instead of 1:1, like what was done on div using css above. I would prefer pure js and no jquery if at all possible. I've tried doing this myself, but I'm rather amateurish when it comes to javascript.
Thanks in advance!
Please see a working codepen here.
The solution is quite simple. On window resize we return the clientHeight of the parent. by dividing the returned value we achieve an integer that is usable as a font-size. We then assign this to the p element.
I hope this solves your problem.
//assigns font-size when document is ready
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
var wrapperHeight = document.getElementById('wrapper').clientHeight;
var relativeFontSize = wrapperHeight / 10 + 'px'; //change 10 to any integer for desired font size
document.getElementById("lorem").style.fontSize = relativeFontSize;
}
};
//then on window resize
window.onresize = function(event) {
var wrapperHeight = document.getElementById('wrapper').clientHeight;
var relativeFontSize = wrapperHeight / 10 + 'px'; //change 10 to any integer for desired font size
document.getElementById("lorem").style.fontSize = relativeFontSize;
};
body {
background-color:white;
}
#wrapper {
width: 95vw;
height: calc(95vw * 9/16);
max-height: 95vh;
max-width: calc(95vh * 16/9);
background: center;
background-color: blue;
background-size:contain;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
font-size:60px;
}
#lorem {
color: aqua;
text-align:center;
position:absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
margin:auto;
}
<div id="wrapper">
<p id="lorem">
This text should scale with div only.
</p>
</div>
How can I correct my code to keep the div in the center of the window when it is resized:
window.addEventListener("resize",handleResize,false);
function handleResize(){
var newwidth = window.innerWidth.value;
var newheight = window.innerHeight.value;
window.resizeTo(newwidth , newheight);
}
There is definitely no need for javascript coding for that: e.g. use auto margins with a parent container that has absolute or relative positioning instead.
You actually do not need to use JavaScript to achieve this. It can be done with pure CSS.
If you still want to use JS, you basically just have to get the window.innerWidth and window.innerHeight and divide them by 2. This will give you a point in the exact center of the window. Then just subtract half of the width from your element and half of the height to offset the left and top position of the element you want to center. This is necessary, because the positioning is relative to the upper left corner of the document.
When your using a CSS solution with an absolute positioned element make sure that the parent elements position is set to relative.
Here is an example with both, JS and CSS centering.
var centerDiv = document.querySelector('.center-js'),
showHideBtn = document.querySelector('.show-hide'),
winW = 0,
winH = 0;
// this is just the button click handler.
showHideBtn.addEventListener('click', function() {
if (centerDiv.style.opacity != 0) {
centerDiv.style.opacity = 0;
this.textContent = "Hide CSS centering";
} else {
centerDiv.style.opacity = 1;
this.textContent = "Show CSS centering";
}
}, false);
// here is the win resize handler;
function windowResize () {
winW = window.innerWidth;
winH = window.innerHeight;
centerDiv.style.top = (winH/2) - (centerDiv.clientHeight/2) + 'px';
centerDiv.style.left = (winW/2) - (centerDiv.clientWidth/2) + 'px';
}
window.addEventListener("resize", windowResize, false);
windowResize();
centerDiv.style.opacity = 1;
html {
position: relative;
min-height: 100%;
font-family: sans-serif;
color: white;
}
div {
text-align: center;
line-height: 200px;
vertical-align: middle;
}
.center-js {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background: black;
opacity: 1;
transition: opacity .5s linear 0s;
z-index: 1020;
}
.center-css {
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
width: 200px;
height: 200px;
background: red;
z-index: 1010;
}
<button class="show-hide">Show CSS centering</button>
<div class="center-js">JS centering</div>
<div class="center-css">CSS centering</div>