- :target
- Синтаксис
- Примеры
- Таблица контента
- HTML
- CSS
- Результат
- Pure-CSS lightbox
- HTML
- CSS
- Результат
- Спецификации
- Поддержка браузерами
- How to target a specific <img> element of a div in CSS?
- How to target a specific <img> element of a div in CSS?
- to ) to your text inside the tags in your index.html file: How to put an image in div with CSS? I would like to have all my images in CSS (the only way I know how is to put them in as background images). But the problem in this solution is you can never let the div take the size of the image. So my question is: what is the best way to have the equivalent of in CSS? you can try it on this link : http://jsfiddle.net/XAh2d/ this is a link about css content http://css-tricks.com/css-content/ This has been tested on Chrome, firefox and Safari. (I’m on a mac, so if someone has the result on IE, tell me to add it) and put this into your css file: otherwise, just use them as plain Take this as a sample code. Replace imageheight and image width with your image dimensions. load image with hidden img when image has been loaded, get width and height dynamically create a div and set width, height and background remove the original img $(document).ready(function() < var image = $(""); var div = $("") image.load(function() < div.css(< "width": this.width, "height": this.height, "background-image": "url(" + this.src + ")" >); $("#container").append(div); >); image.attr("src", "test0.png"); >); Css — How to select first img tag in a div with many img, Edited my answer. In any case, first-of-type would be a better solution overall as it is more specific to the img tag only. If at any point this HTML is modified to include, for example a heading before the images (which wouldn’t be an unreasonable idea), :first-child would break, and the solution would be to use … Setting CSS to an img inside div that has class inside div that has ID I would like to change only the img with alt «SP2». Another problem is that the code has generato. Can I do this? I didn’t completely get the question but try this .image-info > img[alt =»SP2″] it selects the img element having the alt vaue of SP2 You’re looking for a selector like this: That will get the img inside the div with id special-image-2 . If you don’t want or can’t use the id for whatever reason, you could also use: div.image-itself div.image-info img[alt="SP2"] This will match them by div class and the value of the alt attribute of the img . I would, however, recommend using a class to identify between different types of image elements for your use, since the alt text does have a valid and important use for context and accessibility. I add an important and code works. The last code is this: .image-info > img < width:50px; height:50px; background-color:green; >#special-image2 > .image-info > img How to auto-resize an image to fit a div container using, It tells the content how to fit in a specific div container in various way such as preserve that aspect ratio or stretch up and take up as much space as possible. Example 1: This example describes the auto-resize image fit to div container. This example does not contain object-fit property. html. Contain an image within a div? I want to contain an image into a 250 x 250 div, forcing the image to resize but not stretch. How can I do this? By the way, the image will usually be bigger than the div itself, which is why resizing comes into the picture. Here’s a jsfiddle which someone can edit: object-fit , behaves like background-size , solving the issue of scaling images up and down to fit. The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width. Browser Support There’s no IE support, and support in Edge begins at v16, only for img element: https://caniuse.com/#search=object-fit The bfred-it/object-fit-images polyfill works very well for me in IE11, tested on Browserstack: demo. Alternative without polyfill using an image in SVG For Edge pre v16, and ie9, ie10, ie11: You can crop and scale any image using CSS object-fit and object-position . However, these properties are only supported in the latest version of MS Edge as well as all other modern browsers. If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an , and using the viewBox and preserveAspectRatio attributes to do what object-fit and object-position do. http://www.sarasoueidan.com/blog/svg-object-fit/#summary-recap (The author explains the technique thoroughly, and duplicating the detail here would be impractical.) Use max width and max height. It will keep the aspect ratio You have to style the image like this and the container with hidden overflow: Since you don’t want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit. See my example with an image that isn’t a square, it doesn’t stretch Html — How to move image in div with CSS?, 8 Answers. Remove the image name from your declaration and make sure your container is set to position: relative so that your image is absolutely positioned against the right containing element in this instance #OverviewText4. #OverviewText4 < position: relative; >#OverviewText4 img < width: 150px; height: … Источник
- How to put an image in div with CSS?
- Setting CSS to an img inside div that has class inside div that has ID
- Contain an image within a div?
:target
Псевдокласс CSS :target представляет уникальный элемент (целевой элемент) с подходящим id URL-фрагментом.
/* Выбирает элемент с подходящим ID текущего URL-фрагмента */ :target border: 2px solid black; >
Для примера, следующий URL имеет фрагмент (обозначается знаком #), который указывает на элемент с именем section2 :
http://www.example.com/index.html#section2
Следующий элемент будет выбран селектором :target , если текущий URL равен вышеуказанному:
section id="section2">Examplesection>
Синтаксис
Примеры
Таблица контента
Псевдокласс :target может использоваться для выделения части страницы, на которую была сделана ссылка из оглавления .
HTML
h3>Table of Contentsh3> ol> li>a href="#p1">Jump to the first paragraph!a>li> li>a href="#p2">Jump to the second paragraph!a>li> li>a href="#nowhere">This link goes nowhere, because the target doesn't exist.a>li> ol> h3>My Fun Articleh3> p id="p1">You can target i>this paragraphi> using a URL fragment. Click on the link above to try out!p> p id="p2">This is i>another paragraphi>, also accessible from the links above. Isn't that delightful?p>
CSS
p:target background-color: gold; > /* Добавление псевдоэлемента внутрь target-элемента */ p:target::before font: 70% sans-serif; content: "►"; color: limegreen; margin-right: .25em; > /* Стиль italic-элементов без target-элемента */ p:target i color: red; >
Результат
Pure-CSS lightbox
Вы можете использовать псевдокласс :target для создания lightbox без использования JavaScript. Этот метод основан на способности якорных ссылок указывать на элементы, которые изначально скрыты на странице. После этого, CSS изменяет их display на видимый.
Примечание: Более полный pure-CSS lightbox , основанный на псевдоклассе :target — available on GitHub (demo).
HTML
ul> li>a href="#example1">Open example #1a>li> li>a href="#example2">Open example #2a>li> ul> div class="lightbox" id="example1"> figure> a href="#" class="close">a> figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec felis enim, placerat id eleifend eu, semper vel sem.figcaption> figure> div> div class="lightbox" id="example2"> figure> a href="#" class="close">a> figcaption>Cras risus odio, pharetra nec ultricies et, mollis ac augue. Nunc et diam quis sapien dignissim auctor. Quisque quis neque arcu, nec gravida magna.figcaption> figure> div>
CSS
/* Закрываем lightbox */ .lightbox display: none; > /* Открываем lightbox */ .lightbox:target position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; > /* Содержимое lightbox */ .lightbox figcaption width: 25rem; position: relative; padding: 1.5em; background-color: lightpink; > /* Кнопка закрытия */ .lightbox .close position: relative; display: block; > .lightbox .close::after right: -1rem; top: -1rem; width: 2rem; height: 2rem; position: absolute; display: flex; z-index: 1; align-items: center; justify-content: center; background-color: black; border-radius: 50%; color: white; content: "×"; cursor: pointer; > /* Обёртка lightbox */ .lightbox .close::before left: 0; top: 0; width: 100%; height: 100%; position: fixed; background-color: rgba(0,0,0,.7); content: ""; cursor: default; >
Результат
Спецификации
Поддержка браузерами
BCD tables only load in the browser
How to target a specific <img> element of a div in CSS?
It will keep the aspect ratio http://jsfiddle.net/rV77g/ Solution 3: You have to style the image like this and the container with hidden overflow: Solution 4: Since you don’t want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit. Solution 4: With Javascript/Jquery: load image with hidden when image has been loaded, get width and height dynamically create a and set width, height and background remove the original Question: I have this code: I would like to change only the img with alt «SP2».
How to target a specific <img> element of a div in CSS?
I’ve a code of some what like this:
Now my question is how do I target a specific image in CSS when having the above code?
It depends entirely upon which image you want to target. Assuming it’s the first (though the implementations are similar for both) image:
#foo img[src="https://code911.top/howto/bar.png"] < /* css */ >#foo img[src^="bar.png"] < /* css */ >#foo img:first-child < /* css */ >#foo img:nth-of-type(1) < /* css */ >
You can add a class to the images OR
.foo img:first-child < css here >.foo img:last-child
I don’t know why everyone is so fixed on the #foo div. You can target the img tag and not even worry about the div tag. These attribute selectors select by the «begins with».
Or you can select by the exact src.
img[src="https://code911.top/howto/bar.png"] < css >img[src="https://code911.top/howto/cat.png"]
If you want to target them both, then you could use the div id.
For just one of the images, there is no need to worry about the #foo div at all.
div > img:first-child*the first image*/> div > img:last-child*the last image*/>
How To Style the HTML element with CSS, For example, try adding the HTML heading tags (
to ) to your text inside the tags in your index.html file: How to put an image in div with CSS?
I would like to have all my images in CSS (the only way I know how is to put them in as background images).
But the problem in this solution is you can never let the div take the size of the image.
So my question is: what is the best way to have the equivalent of
in CSS?
you can try it on this link : http://jsfiddle.net/XAh2d/
this is a link about css content http://css-tricks.com/css-content/
This has been tested on Chrome, firefox and Safari. (I’m on a mac, so if someone has the result on IE, tell me to add it)
and put this into your css file:
otherwise, just use them as plain
Take this as a sample code. Replace imageheight and image width with your image dimensions.
- load image with hidden img
- when image has been loaded, get width and height
- dynamically create a div and set width, height and background
- remove the original img
$(document).ready(function() < var image = $(""); var div = $("") image.load(function() < div.css(< "width": this.width, "height": this.height, "background-image": "url(" + this.src + ")" >); $("#container").append(div); >); image.attr("src", "test0.png"); >);
Css — How to select first img tag in a div with many img, Edited my answer. In any case, first-of-type would be a better solution overall as it is more specific to the img tag only. If at any point this HTML is modified to include, for example a heading before the images (which wouldn’t be an unreasonable idea), :first-child would break, and the solution would be to use …
Setting CSS to an img inside div that has class inside div that has ID
I would like to change only the img with alt «SP2». Another problem is that the code has generato. Can I do this?
I didn’t completely get the question but try this .image-info > img[alt =»SP2″]
it selects the img element having the alt vaue of SP2
You’re looking for a selector like this:
That will get the img inside the div with id special-image-2 .
If you don’t want or can’t use the id for whatever reason, you could also use:
div.image-itself div.image-info img[alt="SP2"]
This will match them by div class and the value of the alt attribute of the img .
I would, however, recommend using a class to identify between different types of image elements for your use, since the alt text does have a valid and important use for context and accessibility.
I add an important and code works. The last code is this:
.image-info > img < width:50px; height:50px; background-color:green; >#special-image2 > .image-info > img
How to auto-resize an image to fit a div container using, It tells the content how to fit in a specific div container in various way such as preserve that aspect ratio or stretch up and take up as much space as possible. Example 1: This example describes the auto-resize image fit to div container. This example does not contain object-fit property. html.
Contain an image within a div?
I want to contain an image into a 250 x 250 div, forcing the image to resize but not stretch. How can I do this? By the way, the image will usually be bigger than the div itself, which is why resizing comes into the picture.
Here’s a jsfiddle which someone can edit:
object-fit , behaves like background-size , solving the issue of scaling images up and down to fit.
The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.
Browser Support
There’s no IE support, and support in Edge begins at v16, only for img element: https://caniuse.com/#search=object-fit
The bfred-it/object-fit-images polyfill works very well for me in IE11, tested on Browserstack: demo.
Alternative without polyfill using an image in SVG
For Edge pre v16, and ie9, ie10, ie11:
You can crop and scale any image using CSS object-fit and object-position . However, these properties are only supported in the latest version of MS Edge as well as all other modern browsers.
If you need to crop and scale an image in Internet Explorer and provide support back to IE9, you can do that by wrapping the image in an , and using the viewBox and preserveAspectRatio attributes to do what object-fit and object-position do.
http://www.sarasoueidan.com/blog/svg-object-fit/#summary-recap
(The author explains the technique thoroughly, and duplicating the detail here would be impractical.)
Use max width and max height. It will keep the aspect ratio
You have to style the image like this
and the container with hidden overflow:
Since you don’t want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.
See my example with an image that isn’t a square, it doesn’t stretch
Html — How to move image in div with CSS?, 8 Answers. Remove the image name from your declaration and make sure your container is set to position: relative so that your image is absolutely positioned against the right containing element in this instance #OverviewText4. #OverviewText4 < position: relative; >#OverviewText4 img < width: 150px; height: …