CSS 使用CSS在div背景中绘制对角线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18012420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
draw diagonal lines in div background with CSS
提问by Ing. Michal Hudak
I have a div for a preview box:
我有一个预览框的 div:
HTML:
HTML:
<div class="preview-content">PREVIEW</div>
CSS:
CSS:
.preview-content {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAGklEQVQIW2NkYGD4D8SMQAwGcAY2AbBKDBUAVuYCBQPd34sAAAAASUVORK5CYII=) repeat;
width: 100%;
min-height: 300px;
max-height: 300px;
line-height: 300px;
text-align: center;
vertical-align: middle;
font-size: 2em;
}
Question: how to add diagonal lines to div background like in the picture?
问题:如何像图片中那样在div背景中添加对角线?
note: with CSS only if possible
注意:仅在可能的情况下使用 CSS
Thank you in advance.
先感谢您。
采纳答案by AxelPAL
You can do it something like this:
你可以这样做:
<style>
.background {
background-color: #BCBCBC;
width: 100px;
height: 50px;
padding: 0;
margin: 0
}
.line1 {
width: 112px;
height: 47px;
border-bottom: 1px solid red;
-webkit-transform:
translateY(-20px)
translateX(5px)
rotate(27deg);
position: absolute;
/* top: -20px; */
}
.line2 {
width: 112px;
height: 47px;
border-bottom: 1px solid green;
-webkit-transform:
translateY(20px)
translateX(5px)
rotate(-26deg);
position: absolute;
top: -33px;
left: -13px;
}
</style>
<div class="background">
<div class="line1"></div>
<div class="line2"></div>
</div>
Here is a jsfiddle.
这是一个jsfiddle。
Improved version of answerfor your purpose.
为您的目的改进版本的答案。
回答by RobertT
Almost perfect solution, that automatically scales to dimensions of an element would be usage of CSS3 linear-gradient connected with calc() as shown below. Main drawback is of course compatibility. Code below works in Firefox 25 and Explorer 10 and 11, but in Chrome (I've tested v30 and v32 dev) there are some subtle problems with lines disappearing if they are too narrow. Moreover disappearing depends on the box dimensions – style below works for div { width: 100px; height: 100px}
, but fails for div { width: 200px; height: 200px}
for which in my tests 0.8px
in calculations needs to be replaced with at least 1.1048507095px
for diagonals to be shown and even then line rendering quality is quite poor. Let's hope this Chrome bug will be solved soon.
几乎完美的解决方案,自动缩放到元素的尺寸将使用 CSS3 线性渐变与 calc() 连接,如下所示。主要缺点当然是兼容性。下面的代码适用于 Firefox 25 和 Explorer 10 和 11,但在 Chrome(我已经测试过 v30 和 v32 dev)中,如果线条太窄,线条会消失一些微妙的问题。此外,消失取决于框的尺寸——下面的样式适用于div { width: 100px; height: 100px}
,但div { width: 200px; height: 200px}
在我0.8px
的计算测试中失败了,至少需要替换1.1048507095px
为显示对角线,即使这样,线条渲染质量也很差。让我们希望这个 Chrome 错误能尽快得到解决。
.crossed {
background:
linear-gradient(to top left,
rgba(0,0,0,0) 0%,
rgba(0,0,0,0) calc(50% - 0.8px),
rgba(0,0,0,1) 50%,
rgba(0,0,0,0) calc(50% + 0.8px),
rgba(0,0,0,0) 100%),
linear-gradient(to top right,
rgba(0,0,0,0) 0%,
rgba(0,0,0,0) calc(50% - 0.8px),
rgba(0,0,0,1) 50%,
rgba(0,0,0,0) calc(50% + 0.8px),
rgba(0,0,0,0) 100%);
}
<textarea class="crossed"></textarea>
回答by intrepidis
You can use SVG to draw the lines.
您可以使用 SVG 绘制线条。
.diag {
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><path d='M1 0 L0 1 L99 100 L100 99' fill='black' /><path d='M0 99 L99 0 L100 1 L1 100' fill='black' /></svg>");
background-repeat:no-repeat;
background-position:center center;
background-size: 100% 100%, auto;
}
<div class="diag" style="width: 300px; height: 100px;"></div>
Have a play here: http://jsfiddle.net/tyw7vkvm
在这里玩一下:http: //jsfiddle.net/tyw7vkvm
回答by Will
All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:
这个 3 年前的问题的所有其他答案都需要 CSS3(或 SVG)。然而,它也可以只用蹩脚的旧 CSS2 来完成:
.crossed {
position: relative;
width: 300px;
height: 300px;
}
.crossed:before {
content: '';
position: absolute;
left: 0;
right: 0;
top: 1px;
bottom: 1px;
border-width: 149px;
border-style: solid;
border-color: black white;
}
.crossed:after {
content: '';
position: absolute;
left: 1px;
right: 1px;
top: 0;
bottom: 0;
border-width: 149px;
border-style: solid;
border-color: white transparent;
}
<div class='crossed'></div>
Explanation, as requested:
根据要求解释:
Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative spacetriangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:
不是实际绘制对角线,我想到我们可以为与我们想要看到这些线的位置相邻的所谓的负空间三角形着色。我想出的技巧是利用了多色 CSS 边框对角倾斜的事实:
.borders {
width: 200px;
height: 100px;
background-color: black;
border-width: 40px;
border-style: solid;
border-color: red blue green yellow;
}
<div class='borders'></div>
To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:
为了使事情符合我们想要的方式,我们选择一个尺寸为 0 和 LINE_THICKNESS 像素的内部矩形,以及另一个尺寸相反的矩形:
.r1 { width: 10px;
height: 0;
border-width: 40px;
border-style: solid;
border-color: red blue;
margin-bottom: 10px; }
.r2 { width: 0;
height: 10px;
border-width: 40px;
border-style: solid;
border-color: blue transparent; }
<div class='r1'></div><div class='r2'></div>
Finally, use the :before
and :after
pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.
最后,使用:before
和:after
伪选择器和相对/绝对位置作为将上述两个矩形的边框彼此重叠插入到您选择的 HTML 元素中的一种巧妙方式,以生成对角线交叉。请注意,使用细的 LINE_THICKNESS 值(例如 1px)时,结果可能看起来最佳。
回答by Saritha.S.R
Please check the following.
请检查以下内容。
<canvas id="myCanvas" width="200" height="100"></canvas>
<div id="mydiv"></div>
JS:
JS:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle="red";
ctx.moveTo(0,100);
ctx.lineTo(200,0);
ctx.stroke();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
CSS:
CSS:
html, body {
margin: 0;
padding: 0;
}
#myCanvas {
padding: 0;
margin: 0;
width: 200px;
height: 100px;
}
#mydiv {
position: absolute;
left: 0px;
right: 0;
height: 102px;
width: 202px;
background: rgba(255,255,255,0);
padding: 0;
margin: 0;
}
回答by Reverter
you can use a CSS3 transform Property:
您可以使用 CSS3 转换属性:
div
{
transform:rotate(Xdeg);
-ms-transform:rotate(Xdeg); /* IE 9 */
-webkit-transform:rotate(Xdeg); /* Safari and Chrome */
}
Xdeg = your value
Xdeg = 你的价值
For example...
例如...
You can make more div and use a z-index property. So,make a div with line, and rotate it.
您可以制作更多 div 并使用 z-index 属性。所以,用线做一个div,然后旋转它。
回答by Shaw
intrepidis' answeron this page using a background SVG in CSS has the advantage of scaling nicely to any size or aspect ratio, though the SVG uses <path>
s with a fill that doesn't scale so well.
intrepidis在此页面上的回答使用 CSS 中的背景 SVG 具有可以很好地缩放到任何大小或纵横比的优势,尽管 SVG 使用<path>
s 的填充不能很好地缩放。
I've just updated the SVG code to use <line>
instead of <path>
and added non-scaling-stroke
vector-effectto prevent the strokes scaling with the container:
我刚刚更新了要使用的 SVG 代码<line>
,<path>
并添加了non-scaling-stroke
矢量效果以防止笔触随容器缩放:
<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'>
<line x1='0' y1='0' x2='100' y2='100' stroke='black' vector-effect='non-scaling-stroke'/>
<line x1='0' y1='100' x2='100' y2='0' stroke='black' vector-effect='non-scaling-stroke'/>
</svg>
Here's that dropped into the CSS from the original answer (with HTML made resizable):
这是从原始答案中放入 CSS 的内容(HTML 可调整大小):
.diag {
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><line x1='0' y1='0' x2='100' y2='100' stroke='black' vector-effect='non-scaling-stroke'/><line x1='0' y1='100' x2='100' y2='0' stroke='black' vector-effect='non-scaling-stroke'/></svg>");
background-repeat: no-repeat;
background-position: center center;
background-size: 100% 100%, auto;
}
<div class="diag" style="width: 200px; height: 150px; border: 1px solid; resize: both; overflow: auto"></div>
回答by skb
I needed to draw arbitrary diagonal lines inside any div. My issue with the other answers posted is that none of them allowed to draw an arbitrary line from point A to point B without doing the trigonometry yourself for the angles. With javascript & CSS you can do this. Hope it's helpful, just specify a pair of points and you're golden.
我需要在任何 div 内绘制任意对角线。我对发布的其他答案的问题是,没有人允许在不自己对角度进行三角学的情况下从 A 点到 B 点绘制任意线。使用 javascript 和 CSS,您可以做到这一点。希望它有帮助,只需指定一对点,你就是黄金。
const objToStyleString = (obj) => {
const reducer = (acc, curr) => acc += curr + ": " + obj[curr] + ";";
return Object.keys(obj).reduce(reducer, "")
};
const lineStyle = (xy1, xy2, borderStyle) => {
const p1 = {x: xy1[0], y: xy1[1]};
const p2 = {x: xy2[0], y: xy2[1]};
const a = p2.x - p1.x;
const xOffset = p1.x;
const b = p2.y - p1.y;
const yOffset = p1.y;
const c = Math.sqrt(a*a + b*b);
const ang = Math.acos(a/c);
const tX1 = `translateX(${-c/2 + xOffset}px) `;
const tY1 = `translateY(${yOffset}px) `;
const rot = `rotate(${ang}rad) `;
const tX2 = `translateX(${c/2}px) `;
const tY2 = `translateY(#container {
background-color: #BCBCBC;
width: 200px;
height: 200px;
padding: 0;
margin: 0;
}
px) `;
return {
"width": Math.floor(c) + "px",
"height": "0px",
"border-top": borderStyle,
"-webkit-transform": tX1+tY1+rot+tX2+tY2,
"position": "relative",
"top": "0px",
"left": "0px",
"box-sizing": "border-box",
};
};
function drawLine(parent, p1, p2, borderStyle) {
const style = lineStyle(p1, p2, borderStyle);
const line = document.createElement("div");
line.style = objToStyleString(style);
parent.appendChild(line);
}
drawLine(container, [100,5], [25,195], "1px dashed purple");
drawLine(container, [100,100], [190,190], "1px solid blue");
drawLine(container, [25,150], [175,150], "2px solid red");
drawLine(container, [25,10], [175,20], "5px dotted green");
<div id="container">
</div>
.cross {
width:150px;
height: 150px;
border: 2px solid #555;
border-radius: 5px;
position: relative;
background: #efefef;
}
.cross .diag1{
position: absolute;
width:100%; height:100%;
clip-path: polygon(90% 0, 100% 0%, 10% 100%, 0% 100%);
background: #311B92;
}
.cross .diag2{
position: absolute;
width:100%; height:100%;
clip-path: polygon(0 0, 10% 0, 100% 100%, 90% 100%);
background: #1B5E20;
}
回答by Cels
Here is how I did this using the css clip-path
property alongside relativeand absolutepositioning to create a more fancy cross.
下面是我如何使用 cssclip-path
属性以及相对和绝对定位来创建更漂亮的十字架。
<div class="cross">
<div class="diag1"></div>
<div class="diag2"></div>
</div>
.cross {
position: relative;
}
.cross::after {
pointer-events: none;
content: "";
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}
.cross1::after {
background:
linear-gradient(to top left, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%),
linear-gradient(to top right, transparent 45%, rgba(255,0,0,0.35) 46%, rgba(255,0,0,0.35) 54%, transparent 55%);
}
.cross2::after {
background:
linear-gradient(to top left, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%),
linear-gradient(to top right, transparent 45%, rgb(255,0,0) 46%, rgb(255,0,0) 54%, transparent 55%);
opacity: 0.35;
}
div { width: 180px; text-align: justify; display: inline-block; margin: 20px; }
Here is a link to the code on codepenif you'd like to tweak it.
如果您想对其进行调整,这里是codepen 上代码的链接。
回答by user
If you'd like the cross to be partially transparent, the naive approach would be to make linear-gradient
colors semi-transparent. But that doesn't work out good due to the alpha blending at the intersection, producing a differently colored diamond. The solution to this is to leave the colors solid but add transparency to the gradient container instead:
如果您希望十字部分透明,最简单的方法是将linear-gradient
颜色设置为半透明。但这并不好,因为在交点处进行了 alpha 混合,产生了不同颜色的钻石。对此的解决方案是保持颜色为纯色,但为渐变容器添加透明度:
<div class="cross cross1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>
<div class="cross cross2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et dui imperdiet, dapibus augue quis, molestie libero. Cras nisi leo, sollicitudin nec eros vel, finibus laoreet nulla. Ut sit amet leo dui. Praesent rutrum rhoncus mauris ac ornare. Donec in accumsan turpis, pharetra eleifend lorem. Ut vitae aliquet mi, id cursus purus.</div>
##代码##