简体   繁体   English

在CSS中使用:after伪元素将background:url图像居中

[英]Centre a background:url image with :after pseudo element in CSS

In CSS, how do I, 在CSS中,我该如何做,

1) use an :after pseudo element to successfully insert, 1)使用:after伪元素成功插入,

2) a background:url image after some text, 2) background:url一些文字后的background:url图片,

3) that is always centred whenever viewed on a wide large screen or tall small screen? 3)在宽大屏幕或高小屏幕上观看时始终居中吗?

(Example images below.) (下面的示例图片。)

I've tried different things with the code below, but it always aligns the image with the left side of the text, instead of remaining centred as the screen size changes. 我在下面的代码中尝试了不同的方法,但是它始终使图像与文本的左侧对齐,而不是随着屏幕尺寸的变化而保持居中。

Appreciate some help please. 请感谢一些帮助。


Code

div:after { content: ''; background:url("https://ippcdn-ippawards.netdna-ssl.com/wp-content/uploads/2018/07/34-1st-PANORAMA-Mateusz-Piesiak-1.jpg"); width: 1200px; height: 474px; display: block; }


Images 图片

Not correct. 不正确。 This is the current result with above code. 这是上面代码的当前结果。

在此处输入图片说明

Correct. 正确。 Expected result with centre aligned image on wide large screen. 大屏幕上居中对齐图像的预期结果。

在此处输入图片说明

Correct. 正确。 Expected result with centre aligned image on tall small screen. 较高的小屏幕上中心对齐的图像的预期结果。

在此处输入图片说明

I was able to achieve your desired result by putting the text within a p > span tag, and applying the :after element to the outer p . 通过将文本放在p > span标记内,并将:after元素应用于外部p ,可以达到您期望的结果。 Then, I gave the span element a max-width and centered it, so that the image appears to overflow the span container. 然后,我给span元素赋予最大宽度并将其居中,以使图像看起来好像溢出了span容器。 See my solution: 查看我的解决方案:

 p:first-of-type:after { content: ''; background:url("https://ippcdn-ippawards.netdna-ssl.com/wp-content/uploads/2018/07/34-1st-PANORAMA-Mateusz-Piesiak-1.jpg"); width: 1200px; height: 474px; display: block; max-width: 100%; margin: 10px 0; } span { display: block; max-width: 70%; margin: 0 auto; } 
 <p><span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eu ipsum eget elit egestas ultrices. Sed dui mauris, efficitur sit amet malesuada at, dictum quis elit. Pellentesque ac placerat ante. Nulla augue arcu, blandit quis nulla vitae, posuere gravida neque. Aenean leo erat, porttitor maximus nunc non, mollis ultrices dui. Maecenas consectetur eleifend ligula, quis rutrum leo suscipit id. Morbi pulvinar et est sit amet lacinia.</span></p> <p><span>Nulla vitae magna at mi tempus cursus. Vestibulum purus purus, facilisis a lectus ac, gravida porta tellus. Integer auctor justo at tempus ultricies. Mauris ut eleifend nibh. Nullam fermentum dui in sem congue semper. Quisque eget pharetra enim. Aliquam erat volutpat. Donec nec fringilla augue, sed blandit neque. Aliquam sollicitudin, ante id accumsan fermentum, urna turpis lacinia metus, a ullamcorper enim velit vitae diam.</span></p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM