Search code examples
cssimagerotationoverlapadjustment

Rotate image and adjust space


I want to rotate a picture (90 degrees) that is between two boxes. The problem is that the picture overlaps the two boxes in this case.

Example 1: Wrong formatting

CSS:

.box{
    height:50px;
    width:200px;
    background-color:blue;
}

HTML:

<div class='box'>Top</div>
    <img style='transform: rotate(90deg);' src='https://cdn.pixabay.com/photo/2017/12/10/20/56/feather-3010848_960_720.jpg' width='200px'>
<div class='box'>Bottom</div>

Example 2: Desired formatting

There is a solution, but I can not use it because "image-orientation" is not recognized by all browsers (especially mobile devices):

<div class='box'>Top</div>
    <img style='image-orientation: 90deg;' src='https://cdn.pixabay.com/photo/2017/12/10/20/56/feather-3010848_960_720.jpg' width='200px'>
<div class='box'>Bottom</div>

Is there any other solution that a rotated image does not overlap other elements? Or is there any alternative for image-orientation that works with all browsers?


Solution

  • If you are looking to keep the image in a relative space such as a restricted width then I would suggest the following which adds a div tag around the image, uses the before pseudo selector to create an aspect ratio based off of the boxes max with of 1:1 width & height, then absolute positioning the image within that to rotate around a center access point. See code below:

    <style type="text/css">
    .box{
        height:50px;
        width:200px;
        background-color:blue;
    }
    .box--image {     
        position:relative;    
        max-width:200px; 
        outline:solid 1px red;
    }
    
    .box--image:before {
        content:"";
        display:block; 
        padding-top:100%;
    }
    
    .box--image img {    
        left:50%;
        position:absolute;          
        top:50%;
        transform:rotate(90deg) translate(-50%,-50%);
        transform-origin:top left;
        width:200px;
    }
    

    <div class="box">Top</div>
        <div class="box--image"><img src="https://cdn.pixabay.com/photo/2017/12/10/20/56/feather-3010848_960_720.jpg" /></div>
    <div class="box">Bottom</div>