Как обрезать img в css
Перейти к содержимому

Как обрезать img в css

  • автор:

Обрезать углы border CSS

Как обрезать углы у border на css?

Каким методом можно обрезать углы у border на css. Или лучше через canvas, но все же мне кажется что бы без заморочек делать каждую отдельную на canvase, лучше на css??И кстати задний фон меняющийся, вставкой псевдоэлемента треугольника не катит.

Отслеживать
задан 20 апр 2017 в 6:41
Костя Абрамкин Костя Абрамкин
11 1 1 серебряный знак 2 2 бронзовых знака

4 ответа 4

Сортировка: Сброс на вариант по умолчанию

.wrapper < position: relative; margin: 50px; width: 100px; height: 40px; line-height: 40px; font-family: Roboto, sans-serif; font-size: 16px; font-weight: bold; text-align: center; border-top: 2px solid #f00; border-bottom: 2px solid #f00; transform-origin: 50% 100% 0; transform: rotate(270deg); >.wrapper::before, .wrapper::after < position: absolute; content: ''; width: 15px; height: 27px; >.wrapper::before < left: -15px; bottom: -2px; border-left: 2px solid #f00; border-bottom: 2px solid #f00; >.wrapper::after < right: -15px; top: -2px; border-top: 2px solid #f00; border-right: 2px solid #f00; >.corner < position: absolute; width: 21px; height: 21px; transform: 50% 50% 0; transform: rotate(45deg); >.left < top: 3px; left: -11px; border-left: 2px solid #f00; >.right
ГЛАВНАЯ

Отслеживать
ответ дан 20 апр 2017 в 8:16
6,121 3 3 золотых знака 19 19 серебряных знаков 38 38 бронзовых знаков

Писал же, что присутствует задний фон, наложить треугольники из псевдоэлементов не то..В общем решил сделать и отрисовать и на svg, так как лучше выхода не вижу

20 апр 2017 в 8:23

@КостяАбрамкин во-первых: там нет треугольников из псевдоэлементов, во-вторых: в чем проблема изменить фон в моем примере?

20 апр 2017 в 10:19
да спасибо, недопонял
20 апр 2017 в 10:36

Привет, ты можешь это сделать через css. Используя border-radius можно задавть уровень скругления каждого угла отдельно.

border-radius: 30px 0px 30px 0px; 
border-top-left-radius:30px; border-top-right-radius:0; border-bottom-right-radius:30px; border-bottom-left-radius:0; 

Отслеживать
ответ дан 20 апр 2017 в 8:06
Roman Stepanov Roman Stepanov
border-radius не подойдет, посмотрите изображение
20 апр 2017 в 8:09
ну это же не то совсем..border-radius отпало же сразу
20 апр 2017 в 8:17
@soledar10, да, я не заметил что углы острые, в таком случае есть вариант описаный здесь, вот пример
20 апр 2017 в 8:23

* < padding: 0; margin: 0; box-sizing: border-box; >body < height: 100vh; font-size: 1.25rem; padding: 1rem; font-family: 'Segoe UI', sans-serif; background: linear-gradient(to bottom, rgba(4, 34, 66, 1) 0%, rgba(11, 93, 181, 1) 100%); >.btn < position: relative; margin: 30px 0; display: inline-block; vertical-align: top; padding: 8px 25px; color: #A6B0BB; text-transform: uppercase; text-decoration: none; -webkit-transform: rotate(-90deg) translate3d( 0, 0, 0); transform: rotate(-90deg) translate3d( 0, 0, 0); transition: .3s; >.btn:before, .btn:after, .btn>span:nth-of-type(1):before, .btn>span:nth-of-type(1):after, .btn>span:nth-of-type(2):before, .btn>span:nth-of-type(2):after < content: ''; position: absolute; background: rgba(255, 255, 255, .3); transition: .3s; >.btn:before, .btn:after < width: calc(100% - 15px); height: 2px; >.btn:before < top: 0; left: 15px; >.btn:after < bottom: 0; left: 0; >.btn>span < position: absolute; top: 0; left: 0; width: 100%; height: 100%; >.btn>span:nth-of-type(1):before, .btn>span:nth-of-type(1):after < height: calc(100% - 15px); width: 2px; >.btn>span:nth-of-type(1):before < top: 15px; left: 0; >.btn>span:nth-of-type(1):after < top: 0; right: 0; >.btn>span:nth-of-type(2):before, .btn>span:nth-of-type(2):after < height: 22px; width: 2px; -webkit-transform: rotate(45deg); transform: rotate(45deg); >@-moz-document url-prefix() < .btn>span:nth-of-type(2):before, .btn>span:nth-of-type(2):after < width: 2.5px; >> .btn>span:nth-of-type(2):before < top: -3px; left: 7px; >.btn>span:nth-of-type(2):after < bottom: -3px; right: 7px; >.btn:hover < color: #fff; >.btn:hover:before, .btn:hover:after, .btn:hover>span:nth-of-type(1):before, .btn:hover>span:nth-of-type(1):after, .btn:hover>span:nth-of-type(2):before, .btn:hover>span:nth-of-type(2):after

How to resize an image using CSS

Before After

When creating web content, creators pay attention to every detail that contributes to an aesthetically pleasing layout. In order to maintain the highest quality of the website, each element is carefully evaluated. This much attention was not paid to a website a decade ago, but now all these factors have a direct impact on business growth. Here’s an example of a demo website, what will happen if you are not resizing images in CSS. In addition, developers are now more concerned with creating web pages that are responsive. Nowadays, the majority of internet users are using mobile phones and tablets, so it is very important to create a responsive web application in order to broaden your business’s reach.

As a result, the use of responsive testing of websites has increased. It is important for every business to perform a responsive test on its website before it is rolled out to the end users, in order to reach as many customers as possible.

Table of Contents

How to resize images in CSS using the image width attribute

You can resize any image in CSS by applying the width attribute in CSS resizes the image relative to the parent container. Also, it will set the same dimension of the images across all the devices it is viewed upon.

Here’s our image without any CSS applied to it.

baseline image

After applying the width attribute, this is how our image looks. Set the image width to 500px with the following CSS code.

Resizing image using Image Width Attribute in CSS

How to resize a responsive image using CSS

Method 1: Resizing a responsive image using the max-width and max-height property

It is really not convenient when the size of the image exceeds the size of the parent container, the max-width and max-height attribute limits the size of the image to not go more than the desired property. The previous method was not much efficient as you would not get a responsive layout when the image is viewed on several devices. The effective solution is to use the max-width property.

Let’s set the width of the image to 50% to stretch it across half of the entire screen, and it will revert the same result irrespective of the devices it is viewed upon.

Resizing a responsive image using the max-width property

Resizing a responsive image using the max-height property

Furthermore, you can also apply the value as auto to the max-height or max-width attribute to prevent any overlapping of any default dimension. This is useful to prevent the image from getting distorted.

Method 2: Resizing a responsive image using the Object-fit property

The object-fit property is used to adjust the dimensions of the image to fit it inside the container it is placed upon. It can be applied to both photos as well as videos so as to fit them realistically into the content box. There can be five values to the object-fit attribute, fill, cover, contain, none, and scale-down.

Let’s apply the object-fit property and see the results.

  • fill: It resizes the image to fit the content box even if it has to stretch or squish the image.
  • cover: It resizes the image to fit the content box without maintaining the aspect ratio of the image. The image will be clipped to fit if the aspect ratio of the content box doesn’t match the image.
  • contain: It resizes the image to fit the given content box maintaining the content box.
  • none: It doesn’t resize the image at all.
  • scale-down: It resizes the image to its smallest version as if it is specified as none or contain.
Method 3: Resizing a responsive image using the background-size property

Another method is to use the background-size property to set the size of the element’s background image. Let’s try this property to set the responsive background image.

  • Using contain value with no-repeat

Baseline Image

Resizing Background Image using Contain Value

Resizing Background Image using Cover Value

Resizing Background Image using Numerical Value

Values of background-size property

The values of background-size property can be specified in the following ways.

  • Using the values contain or cover .
  • Using the values of either width or height, the non-specified value will be specified as auto.
  • You can also set the values of both width and height in either pixels, percentages, or more.

How to Test the Responsiveness of the Resized Image

Testing Responsiveness of Images on Real Devices is a must to ensure it renders correctly on different devices of varying resolutions and screen sizes. Follow the easy steps below to test image responsiveness on real devices:

Step 1: Open BrowserStack Responsive Dashboard and enter the URL of the webpage containing the responsive image. If you have created a website on your local machine, you must host your website to test its responsiveness on BrowserStack Responsive.

BrowserStack Responsive Dashboard

Step 2: To check responsiveness, click Check.

Step 3: The user can check how the site appears on a certain device after choosing it.

Choosing device on BrowserStack Responsive Dashboard

Free Responsive Test on Commonly Used Resolutions

Try testing the responsiveness of your website on real devices.

Summing it up

The ability to resize images using CSS is an integral part of web design. This tutorial, explained how to resize images in CSS for responsive websites. For businesses, paying attention to every aspect of their digital presence is critical since even the tiniest error could have a big impact.

Resizing ensures that images are placed correctly inside their containers. Using max-width and max-height properties of CSS helped prevent the image from exceeding its parent container’s size. Thus, helped create a clean responsive website design. When customizing backgrounds with CSS, use the background-size attribute for seamless background resizing.

However, it is also crucial to perform responsive testing on your website to ensure that the design renders well on devices of different screen sizes and resolution. Thereby, making is ready to reach a wider audience. BrowserStack’s Responsive Testing Tool helps you test the responsiveness of your website on various desktop and mobile devices, helping you get a real look and feel of the website.

CSS — как обрезать изображение без изменения пропорций

При подготовке изображений для Web нередко появляется необходимость обрезать их, чтобы выделить нужные части изображения и отсечь ненадобные. Не считая чисто художественных суждений, такая обрезка либо, как ее еще именуют, кадрирование, нужна для уменьшения объема файла. Чем меньше изображение, тем меньше объем его файла, и тем резвее оно загружается на web страничку.Нередко возникает надобность заключать изображения в блок зафиксированного объема. В предоставленном случае возникает неувязка: как записать картину в блок в отсутствии утраты соотношения.Естественно, разрешено отрезать и масштабировать рисунки по прибавления их на интернет-сайт либо кадрировать на серверном языке (к примеру PHP), а разрешено изготовить некоторый «аналог» на обычный CSS. В предоставленном случае, отрезка станет проистекать сообразно вертикали. То имеется, сообразно ширине картина станет проникать вполне, а сообразно вышине обрезаться.

Сущность предоставленного способа в том, будто картина станет вписана в блок конкретных объемов. Все будто никак не станет проникать в данный блок станет укрыто. Обрамляющий блок станет обладать те ведь наиболее характеристики, будто и картина. Потому, его разрешено станет владеть и сглаживать этак ведь, как и обыденную картину. Вариант, естественно, никак не безупречный, однако действующий.

 .img < display: inline-block; width: 200px; height: 200px; overflow: hidden; border: 5px solid #FFFFFF; background: #FFFFFF; outline: 1px solid #CCCCCC; margin: 10px; >.img img 

Оригинал:

Что получилось:

Как обрезать img в пятиугольник?

5f1ae24ef36c1084074969.png

Нужно обрезать картинки вот так, на фото используется clip-path, но т.к. ie его не поддерживает мне нужен другой способ. Посоветуйте что-нибудь пожалуйста.

  • Вопрос задан более трёх лет назад
  • 274 просмотра

Комментировать
Решения вопроса 0
Ответы на вопрос 3
помогло? отметь решением!

Генерируйте на севере png или что-то подобное с прозрачным фоном. Ну, или забейте на IE (что правильнее)

Ответ написан более трёх лет назад
Комментировать
Нравится Комментировать

develx

Web developer

1. В IE изображение будет прямоугольным — верстка не развалится (graceful degradation).
2. Нужна поддержка IE, значит clip-path и само изображение должны быть заинлайнены внутри svg в html документе. пример https://jsfiddle.net/f8tcxooy/ — реализуйте, если есть необходимость

Ответ написан более трёх лет назад
Комментировать
Нравится Комментировать

один их вариантов
clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%);

Ответ написан более трёх лет назад
Rillai @Rillai Автор вопроса
(на фото используется clip-path, но т.к. ie его не поддерживает мне нужен другой способ. )
Ваш ответ на вопрос

Войдите, чтобы написать ответ

html

  • HTML
  • +1 ещё

Как пофиксти проблему с амперсантом?

  • 1 подписчик
  • 14 часов назад
  • 66 просмотров

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *