简体   繁体   English

在CSS中操作div SVG背景viewBox进行响应式设计

[英]Manipulating an div SVG background viewBox in CSS for responsive design

I have a div element which has an SVG image as a background and position-x: right . 我有一个div元素,该元素具有SVG图像作为背景和position-x: right The div contains two h1 lines whose length differs from page to page. div包含两条h1行,各行的长度各不相同。

I want to apply a script or a CSS rule that changes the viewBox of the SVG depending on the screen width. 我想应用脚本或CSS规则来根据屏幕宽度更改SVG的viewBox。 The final object should be able to crop the left side of the SVG according to screen-element proportions. 最终对象应该能够根据屏幕元素的比例裁剪SVG的左侧。

Is there a way to make this possible? 有没有办法使之成为可能?

Here are some mockups. 这是一些样机。 简短的文字示例

长文本示例

Currently, I use the following CSS rules: 当前,我使用以下CSS规则:

 h1{ font-family: "Tahoma", sans-serif; font-size: 52px; } .div { background: #000 no-repeat right; /* think of the SVG from the examples here */ color: #fff; display: inline-block; padding: 56px 180px 56px 7%; margin-right: auto; } .container{ background: none; margin: 0; padding: 0; } @media(max-width: 450px){ .div { padding: 20px 50px 20px 7%; } } 
 <div class="div"> <div class="container"> <h1>Feel free</h1> <h1>To change this</h1> </div> </div> 

However, on mobile screens it may end up like this: 但是,在手机屏幕上,它可能最终会像这样: 移动示例

Also, though I apply position-x: right on the SVG, it doesn't quite end up on the right side of the div: 另外,尽管我在SVG上应用了position-x: right :,但它并没有完全位于div的右侧: 在此处输入图片说明

Is there a clean way to do this? 有没有一种干净的方法可以做到这一点? I am open for JavaScript solutions as well. 我也欢迎JavaScript解决方案。

I think you might be approaching this the from the wrong angle (or at least a more difficult one). 我认为您可能是从错误的角度(或者至少是一个更困难的角度)来解决这个问题。 From what I can tell you're going to need rules for every single page. 据我所知,您将需要每个页面的规则。

A better solution would be a way to style it where the styling adjusts to the width of the content. 更好的解决方案是在样式调整为内容宽度时对其进行样式设置的方法。 I would wrap the text in an DIV and use a pseudo element for the angled edge. 我会将文本包装在DIV中,并为角度边缘使用伪元素。 With this approach the DIV will expand to whatever the size the text is. 通过这种方法,DIV可以扩展到任何文本大小。

 .featured { position: relative; } .text, .text:after { background-color: skyblue; } .text { position: absolute; top: 150px; left: 0; display: inline-block; padding: 1rem 2rem; z-index: 5; } .text:after { display: block; content: ''; position: absolute; top: 0; bottom: 0; right: -20px; width: 50px; transform: skew(-15deg); z-index: -1; } 
 <div class="featured"> <img src="https://placehold.it/1200x400/fc0/&text=bg"> <div class="text"> <h2>Some text goes here.</h2> <h2>Some other text goes right here.</h2> </div> </div> 

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

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