htmlcsssasslessstretch

How to make vertical and horizontal center without stretching image with css?


If I set width and height using css (width:100%; height:100%), image will be stretched, and It looks ugly. How to Fill images without stretching? What is more, how to make vertical and horizontal center?


Solution

  • Using only HTML and CSS:

    HTML

    <div class="fill"></div>
    

    CSS

    .fill {
        overflow: hidden;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-size: cover;
        background-position: center;
        background-image: url('path/to/image.jpg');
    }