I want to achieve like this example:
I know how to do it by using background-image in css but I dont want to do it as the object could be anything. It could be img, svg, canvas, or even a div. Is there any other solutions?
I want to achieve like this example:
I know how to do it by using background-image in css but I dont want to do it as the object could be anything. It could be img, svg, canvas, or even a div. Is there any other solutions?
I wrote years ago how to do exactly that:
https://codepen.io/vsync/pen/DpmnK
.box{
position:absolute; /* or relative */
/* assume box has height limit lower than the image height */
height: 100px;
/* demo-related styles: */
margin: auto;
top:0; right: 0; bottom: 0; left: 0;
background: lightblue;
}
/* The magic: */
.box > img{
position:relative;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
<div class='box'>
<img src="https://via.placeholder.com/150x150/FF0000" />
</div>
.wrapper{
display: flex;
align-items: center;
height: 100vh;
padding: 100px 0;
}
.hoder {
width: 100%;
height: 200px;
background: green;
text-align: center;
position: relative;
}
.center{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div class="wrapper">
<div class="hoder">
<div class="center">
<img src="https://picsum.photos/id/237/200/300" alt="">
</div>
</div>
</div>
Try this:
.parent {
background-color: black;
height: 300px;
display: flex;
justify-content: center;
position: relative;
top: 100px;
}
.img {
height: 150%;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
<div style="position: relative;">
<div class="parent">
<img src="https://via.placeholder.com/300" class="img">
</div>
</div>
Assuming parent has non static position, you can do something like this:
.container {
height: 100vh;
width: 100vw;
position: relative;
}
.big-img{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
<div class="container">
<img class="big-img" src="https://images.unsplash.com/photo-1558980394-34764db076b4?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80">
</div>
Explanation: What you are doing is placing the top-left corner of the child image 50% below the top and 50% to the right of the top-left corner of the parent container. You then have to transform the child image to translate it's position to the actual center of the parent container
Codepen: https://codepen.io/anon/pen/mNpjJa