- CSS Image Styling
- margin
- border
- padding
- width and height
- Keeping Image Aspect Ratio
- Width and Height as Percentages
- max-width and max-height
- min-width and min-height
- Responsive Images
- CSS Styling Images
- Example
- Example
- Thumbnail Images
- Example
- Example
- Responsive Images
- Example
- Center an Image
- Example
- Polaroid Images / Cards
- Example
- Transparent Image
- Example
- Image Text
- Example
- Image Filters
- Example
- Image Hover Overlay
- Example
- Example
- Example
- Example
- Example
- Example
- Flip an Image
- Example
- Responsive Image Gallery
- Example
- Image Modal (Advanced)
- Example
- Отступы вокруг изображения
CSS Image Styling
CSS can be used to style images inside HTML pages. By images I mean images included using the img HTML element. In this text will cover the options you have for styling images via the img element with CSS.
margin
The margin CSS property enables you to set the distance between the image and adjacent HTML elements. CSS margins are covered in more detail in my tutorial about margins in CSS.
Actually, the margin is the distance between the border around the image to the adjacent HTML elements. If the image has no border, the margin will be the distance between the edge of the image padding to adjacent HTML elements. If the image has no padding, the margin will be the distance between the image itself to adjacent HTML elements.
border
You can set borders on an image ( img element) using the border CSS property. CSS borders are covered in more detail in my tutorial about CSS borders.
Here is an example that sets a border on an image:
This example CSS rule sets a 1 pixel gray border around all img elements which have the CSS class withBorder ( ). Here is how an image looks with the above border styling applied:
padding
The padding CSS property sets the distance between the image and its border. Padding is covered in more detail in my tutorial about padding in CSS.
Here is an example that sets both padding and border around an image:
Here is how the image looks with these CSS styles applied:
width and height
You can use the width and height CSS properties to set the width and height of an image. The width and height CSS properties are also covered in my tutorial about the CSS box model.
If you set a width and height that is different from the image’s own width and height, then the browser will scale the image up or down to match the width and height you set. Here are some width and height CSS examples:
img.scaledUp < width: 300px; height: 150px; >img.scaledDown
Here is what the images would look like with the above styles applied. The first image shows the natural size of the image. The two following images are scaled up and scaled down.
Keeping Image Aspect Ratio
Scaling images by setting both width and height may result in distorted images, meaning the aspect ratio between width and height might be lost. To scale an image while preserving aspect ratio, set only the width or height CSS property. The browser will then calculate the other aspect (height, if width is set, or width, if height is set) based on the set width or height, so the aspect ratio of the image is kept. Here are two examples which set only the width and height :
img.scaledUp < width: 300px; >img.scaledDown
Here are what the images would look like when rendered:
Width and Height as Percentages
You can set width and height to percentages. In that case the image will get a width and / or height which is a percentage of the width or height of its parent HTML element. Here is an example:
This examples sets the width of the image to 25% of its parent HTML element width. If the parent HTML element is scaled up or down in size, so is the image.
max-width and max-height
You can set a maximum width and height for the image using the max-width and max-height CSS properties.
Setting a maximum width or height can be useful if the image is using percentages as width or height. In case the user maximizes the browser, perhaps you don’t want your image to be scaled up to fill the full browser window (or whatever size the image’s parent element has). Setting a maximum width and height might be useful in that case. Here is an example setting a max-width on an image:
This example CSS rule sets the width of the img element with the CSS class withMaxWidth to 100% of its parent element. However, the example limits the image to a maximum width of 500px . Once the image reaches a width of 500 pixels, the browser will no longer scale it up, regardless of the width of the parent element.
min-width and min-height
The min-width and min-height CSS properties work like the max-width and max-height CSS properties, except the set a minimum width and height for the image (or whatever HTML element they are applied to.
Responsive Images
Responsive images are images that are part of a responsive web design and which behave accordingly. A responsive web design is a web design which is capable of responding sensibly to the device it is being viewed on, whether that device be a mobile phone, tablet, laptop, desktop or TV.
On a small screen you might want to show smaller images than on a large screen. You might also want to limit the size of an image to fit inside smaller screens (using max-width ).
As part of my responsive, mobile friendly web design tutorial I have a text which specifically explains how to implement responsive images.
CSS Styling Images
Use the border-radius property to create rounded images:
Example
Example
Thumbnail Images
Use the border property to create thumbnail images.
Example
img <
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 150px;
>
Example
img <
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 150px;
>
img:hover box-shadow: 0 0 2px 1px rgba(0, 140, 186, 0.5);
>
Responsive Images
Responsive images will automatically adjust to fit the size of the screen.
Resize the browser window to see the effect:
If you want an image to scale down if it has to, but never scale up to be larger than its original size, add the following:
Example
Tip: Read more about Responsive Web Design in our CSS RWD Tutorial.
Center an Image
To center an image, set left and right margin to auto and make it into a block element:
Example
Polaroid Images / Cards
Example
div.polaroid <
width: 80%;
background-color: white;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
>
div.container text-align: center;
padding: 10px 20px;
>
Transparent Image
The opacity property can take a value from 0.0 — 1.0. The lower value, the more transparent:
Example
Image Text
How to position text in an image:
Example
Image Filters
The CSS filter property adds visual effects (like blur and saturation) to an element.
Note: The filter property is not supported in Internet Explorer or Edge 12.
Example
Change the color of all images to black and white (100% gray):
Tip: Go to our CSS filter Reference to learn more about CSS filters.
Image Hover Overlay
Create an overlay effect on hover:
Example
Example
Example
Example
Example
Example
Flip an Image
Move your mouse over the image:
Example
Responsive Image Gallery
CSS can be used to create image galleries. This example use media queries to re-arrange the images on different screen sizes. Resize the browser window to see the effect:
Example
.responsive <
padding: 0 6px;
float: left;
width: 24.99999%;
>
@media only screen and (max-width: 700px) .responsive width: 49.99999%;
margin: 6px 0;
>
>
@media only screen and (max-width: 500px) .responsive width: 100%;
>
>
Tip: Read more about Responsive Web Design in our CSS RWD Tutorial.
Image Modal (Advanced)
This is an example to demonstrate how CSS and JavaScript can work together.
First, use CSS to create a modal window (dialog box), and hide it by default.
Then, use a JavaScript to show the modal window and to display the image inside the modal, when a user clicks on the image:
Example
// Get the modal
var modal = document.getElementById(‘myModal’);
// Get the image and insert it inside the modal — use its «alt» text as a caption
var img = document.getElementById(‘myImg’);
var modalImg = document.getElementById(«img01»);
var captionText = document.getElementById(«caption»);
img.onclick = function() modal.style.display = «block»;
modalImg.src = this.src;
captionText.innerHTML = this.alt;
>
// Get the element that closes the modal
var span = document.getElementsByClassName(«close»)[0];
// When the user clicks on (x), close the modal
span.onclick = function() <
modal.style.display = «none»;
>
Отступы вокруг изображения
Для любого изображения можно задать пустые отступы по горизонтали и вертикали с помощью параметров hspace и vspace тега . Особенно это актуально при обтекании рисунка текстом. В этом случае, чтобы текст не наезжал плотно на изображение, необходимо вокруг него добавить пустое пространство (пример 1).
Пример 1. Добавление отступов вокруг изображения
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Результат данного примера приведен ниже. Текст отступает от изображения на 10 пикселов.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Тот же результат можно получить и с помощью стилей, используя стилевой атрибут margin , как показано в примере 2.
Пример 2. Добавление отступов с помощью стилей
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
!DOCTYPE>
Удобство применения стилей заключается в том, что можно задать разные отступы для каждой стороны изображения. Для этого надо перечислить через пробел значения отступов, начиная с верхнего. В примере 2 верхний отступ задается как 10 пикселов, правый — 15, нижний — 20, а левый — 7 пикселов. Если все отступы должны быть одинаковы, поставьте только одно число.