Flexible Content in CSS

Prevent Overlapping

Let’s have the following website that displays the CSS logo as an image. The image is displayed in its original size.

flexible_content_1

The page is produced by the the following html and css file:


<!DOCTYPE html>
<html>
<head>
<title>CSS overlapping</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="imageholder">
<div class="centering">
<img class="img" src="css.jpg">
</div>
</div>
</body>
</html>

view raw

index.html

hosted with ❤ by GitHub


html, body {
background-color: lightgrey;
margin: 0;
}
.imageholder {
position: absolute;
margin: 10% auto;
width: 100%;
height: 60%;
background-color: darkblue;
}
.centering {
margin: 0 auto;
width: 40%;
height: 100%;
background-color: black;
}

view raw

main.css

hosted with ❤ by GitHub

As soon as the page is decreased, the image overlaps its intended area (black area) which is not desired.

flexible_content_2

The solution to this problem is to introduce both the properties max-width and max-height. They will prevent the image from overlapping to other areas.


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

view raw

main.css

hosted with ❤ by GitHub

Keeping aspect ratio

Keeping aspect ratios in responsive websites is primarily important for videos and images. In the following it is show how the aspect ratio can be kept. Again there is a index.html and a main.css:


<!DOCTYPE html>
<html>
<head>
<title>CSS aspect ratio</title>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div class="container">
<div class="element">
</div>
</div>
</body>
</html>

view raw

index.html

hosted with ❤ by GitHub


html, body {
background-color: lightgrey;
margin: 0;
}
.container {
position: relative;
height: 0;
padding-bottom: 25%;
background-color: red;
}
.element {
position: absolute;
height: 100%;
width: 100%;
background-color: darkblue;
}

view raw

main.css

hosted with ❤ by GitHub

The relevant part here is to set height:0 and padding-bottom: 25% in the container selector. This will create a container that is 4 times as width as height because a padding is always calculated of the elements width. The aspect ratio is even kept if the browser size is changed.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s