CSS Object Fit - Detailed Overview

Introduction to CSS Object Fit

The object-fit property in CSS specifies how an img or video should be resized to fit its container. It can take various values to control how the content fits within its container.

Examples of Object Fit

The following examples demonstrate different values for the object-fit property:

Cover

Example Image - Cover

Contain

Example Image - Contain

Fill

Example Image - Fill

None

Example Image - None

Scale Down

Example Image - Scale Down
<div class="fit-container">
<img src="https://www.shariqsp.com/image1.jpg" alt="Example Image">
</div>

CSS Used in Examples

The following CSS was used for styling the examples:

/* General Styles */
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f0f0f0;
}

header {
    background-color: #333;
    color: #fff;
    padding: 20px 0;
    text-align: center;
    margin-bottom: 20px;
}

h1 {
    margin: 0;
    font-size: 32px;
}

.container {
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    border-radius: 10px;
    max-width: 800px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.example {
    border: 1px solid #ddd;
    padding: 10px;
    margin-top: 10px;
    border-radius: 5px;
    background-color: #fafafa;
    text-align: center;
}

.example img {
    max-width: 100%;
    height: auto;
}

.fit-container {
    width: 300px;
    height: 200px;
    margin: 10px auto;
    overflow: hidden;
    position: relative;
}

.fit-container img {
    width: 100%;
    height: 100%;
    object-fit: cover; /* Default value for demonstration */
}

/* Additional classes to demonstrate different object-fit values */
.fit-container.contain img {
    object-fit: contain;
}

.fit-container.fill img {
    object-fit: fill;
}

.fit-container.none img {
    object-fit: none;
}

.fit-container.scale-down img {
    object-fit: scale-down;
}