【问题标题】:Make border width a half of its parent's height element using css?使用css将边框宽度设为其父元素高度的一半?
【发布时间】:2018-09-28 22:06:22
【问题描述】:

这是我想做的:

我正在使用具有 0px 高度和宽度的 css 边框属性制作形状(三角形)。形状应与其父级高度相同。它的父母身高是未知的和变化的。这如何通过使用 css 来完成。(不使用 Javascript)

我也尝试使用百分比(border-width: 50%;)

这是代码,但不是必需的!

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">
        html, body {
            height: 100%;
        }
        body {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        body > div {
            border: 2px solid blue;
            width: 400px;
            height: 70px;/* unknownHeight = 70px */
            display: flex;
            flex-direction: row;
        }
        .shape {

            border-width: 35px; /* unknownHeight/2 = 35px */
            border-style: solid;

            border-top-color: transparent;
            border-right-color: transparent;
            border-bottom-color: red;
            border-left-color: red;
        }
        .stableDiv {
            flex: 1;
        }
    </style>
</head>

<body>
    <div>
        <div class="stableDiv"></div>
        <div class="shape"></div>
    </div>
</body>
</html>

【问题讨论】:

  • 请在发帖前查看How to create a Minimal, Complete, and Verifiable example。希望您至少尝试并提供一些代码。
  • 基本上,你不能。没有将widthheight 关联起来的CSS 机制。你可以反过来做,但不能那样做。
  • 宽度也需要调整大小还是三角形可以拉伸?否则,伪和线性渐变将足以有效地绘制该形状。如果角度需要保持在45度,很快就会填满整个盒子长大??

标签: html css flexbox css-shapes


【解决方案1】:

因为你没有提到任何代码。我可以建议您访问以下链接以使用 CSS 生成三角形。

http://apps.eky.hk/css-triangle-generator/

https://css-tricks.com/examples/ShapesOfCSS/

【讨论】:

  • 制作三角形不是问题。问题是与父母的高度相同(这是未知的)。你能帮忙#Yashwardhan_Pauranik
【解决方案2】:

本质上,您不能使用边框或标准 HTML 元素来执行此操作,因为没有将元素的宽度与高度相关联的 CSS 机制。

但是,您可以使用定位的方形 SVG 和三角形多边形

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

div {
  height: 50px;
  width: 80%;
  margin: 1em auto;
  border: 1px solid grey;
  position: relative;
}

.taller {
  height: 100px;
}

svg {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
}

svg polygon {
  fill: red;
}

div:hover polygon {
  fill: blue;
}
<div>
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewbox="0 0 100 100">
  <polygon points="0,0 0,100 100,100"/>
</svg>
</div>

<div class="taller">
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewbox="0 0 100 100">
  <polygon points="0,0 0,100 100,100"/>
</svg>
</div>

【讨论】:

    【解决方案3】:

    以下是使用 css 边框属性绘制三角形的方法:

    #shape {
      border-width: 50px 50px 0 0;
      border-color: transparent red transparent transparent;
      border-style: solid;
    }
    <div id="shape">
    </div>

    https://jsfiddle.net/zjpen5at/1/

    由于不清楚,因此不确定这是否能回答您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      相关资源
      最近更新 更多