在CSS中,我们可以使用多种方式插入图片,并且能够设置图片与背景同样宽度。 一、插入图片 1.通过img标签插入图片 html <p>这是一个通过img标签插入的图片:&a
html
<p>这是一个通过img标签插入的图片:</p>
<pre><img src="images/picture.jpg" alt="图片说明">
2.通过background-image属性插入图片 css p { background-image: url(images/picture.jpg); background-repeat: no-repeat; background-position: center; }3.通过::before伪元素插入图片
css p::before { content: ""; background-image: url(images/picture.jpg); background-repeat: no-repeat; background-position: center; display: inline-block; width: 150px; height: 150px; margin-right: 10px; }
这是一个通过::before伪元素插入的图片:
/* CSS代码 */
p::before {
content: "";
background-image: url(images/picture.jpg);
background-repeat: no-repeat;
background-position: center;
display: inline-block;
width: 150px;
height: 150px;
margin-right: 10px;
}
二、设置图片与背景一样宽度
1.通过background-size属性设置 css p { background-image: url(images/picture.jpg); background-repeat: no-repeat; background-position: center; background-size: cover; }2.通过伪元素插入图片,并设置宽度百分比
css p::before { content: ""; background-image: url(images/picture.jpg); background-repeat: no-repeat; background-position: center; display: block; width: 100%; padding-top: 50%; /* 高度为宽度的50% */ }以上就是插入图片和设置宽度的方法,你也可以根据实际情况选择不同的方式。
粉丝
0
关注
0
收藏
0