- 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
- 2 Simplest Ways to Add Padding Around the Image in HTML
- Here’s How to Add Padding Around the Image in HTML
- Method #1: Using hspace and vspace Attributes
- Method #2: Using CSS Padding Property
- CSS и HTML: cвойства изображений
- Свойства изображений
- Размеры, ширина, высота – width, height
- Отступы, поля – margin и padding
- Рамка – border
- Картинка на фоне – background
- Ссылки:
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.
2 Simplest Ways to Add Padding Around the Image in HTML
Wanna know how to add padding around the image in HTML? Here I explained two simple methods to add padding around any image using HTML.
Padding around the image means the blank space around the image. If you’re attaching an image to your website using HTML, then you would need to add padding around it and here in this post, I will guide you how to do so. I’ve 2 very simple methods to add padding around the image in HTML.
Here’s How to Add Padding Around the Image in HTML
The two simple methods for setting up the padding around the image in HTML are following:
Method #1: Using hspace and vspace Attributes
Both of these attributes are used to specify the whitespace around the image. The hspace puts white space on left and right side of an image whereas vspace attribute specifies white space on top and bottom side of an image.
Here’s the syntax of using hspace and vspace attributes:
Now, here’s an example of an image with 20 pixels of padding around it with the help of hspace and vspace attributes:
This is some text. This is some text. This is some text.
Just use this syntax to add padding or margin around the image. Isn’t it easy to add padding around image using hspace and vspace attributes?
But, before using it anywhere you should be careful of its compatibility issues. Both of these attributes of are not supported in HTML5. So, you can use CSS instead. And the second method is all about setting up the padding around the image using CSS.
Method #2: Using CSS Padding Property
As I above told you hspace and vspace attributes don’t work in HTML5 but CSS works in almost every new technology.
Here’s an example of using padding property in HTML inside tag:
The padding property can have from one to four values.
padding: 25px 50px 75px 100px;
- top padding is 25px
- right padding is 50px
- bottom padding is 75px
- left padding is 100px
padding: 25px 50px 75px;
That’s all guys! I hope with the help of this article you will be able to add padding around any image in HTML. Let me know which method you liked more? Or is there anybody who wanna share any other method for the same? Our comment box is waiting for you. 😉
CSS и HTML: cвойства изображений
img – одиночный тег. У него 2 обязательных атрибута: src типа путь к файлу и alt типа текст.
Распространенные форматы изображений: jpeg, png (не имеет стандартной иконки), svg, webp:
Изображения бывают растровые и векторные. Растровые состоят из квадратных пикселей. Векорные – из кривых и других графических примитивов, правил их построения в изображение. svg – векторный формат.
Изображение в HTML – по умолчанию строчный блок (display: inline-block;). Это значит, что картинка в тексте воспринимается браузером как элемент текста.
Свойства изображений
Размеры, ширина, высота – width, height
- ширина, width: 100px;
- минимальная ширина, min-width: 100px;
- максимальная ширина, max-width: 100px;
- высота, height: 100px;
- минимальная высота, min-height: 100px;
- касимальная высота, max-height: 100px;
Отступы, поля – margin и padding
Поля страницы можно инспектировать в браузере по нажатию F12, вкладка Elements
Рамка – border
- рамка, обобщенное правило. border: 2px dashed blue;
- радиус скругления рамки. border-radius: 5px;
- Скруглить квадрат до круга – border-radius: 50%; Пример: аватарка
Картинка на фоне – background
- background-image устанавливает картинку на фоне по ее url-адресу
- background-position (top center, right top и т.д.)
- background-size (cover, значения 200px 200px)
- background-repeat (значения: repeat-x no-repeat repeat-y)
- background-attachment Поведение фона при скроллинге (значения: scroll, fixed, local)
- background-origin Опредеяет, где отрисовывать фон (значения: border-box, padding-box, content-box, inherit)
- background-clip (значения: border-box по умолчанию, padding-box, content-box, inherit) Примеры.
- background-color (цвет фона)
- background: white url(«image.jpg») no-repeat 50% 0; Общее свойство, описывающее фон страницы.
- background: url(/media/blog/example_image_1.jpg) center no-repeat;
Солнечная система: статистика (background-size: cover; background-position: center;)
Статистика пилотируемой космонавтики (background-repeat: no-repeat; background-position: bottom; background-color: black;)