代码之家  ›  专栏  ›  技术社区  ›  sazr

在三角形容器中正确定位元素

  •  1
  • sazr  · 技术社区  · 9 年前

    我有一个三角形的容器div,里面可以是任何东西( p , label , input 等等)。我的三角形看起来不错,但元素位于三角形之外。

    如何使我的triangle CSS3足够健壮,能够处理任何内容并正确定位它们?

    目前看起来像第一张图片,我的目标是第二张图片:

    enter image description here enter image description here

    JSIDLE: https://jsfiddle.net/hkunofLk/

    .arrow-down {
        width: 0; 
        height: 0; 
        border-left: solid transparent;
        border-right: solid transparent;
    
        border-top: solid #f00;
    
        overflow: visible;
    }
    
    .arrow-md {
        border-width: 200px;
    }
    
    input {
        width: 200px;
        height: 75px;
    }
    
    <div class="arrow-md arrow-down">
        <label for="usr">Name:</label>
        <input type="text" class="form-control input-lg" id="usr">
    </div>
    
    2 回复  |  直到 9 年前
        1
  •  1
  •   Nora    9 年前

    下面是一个JSIDLE示例: https://jsfiddle.net/hkunofLk/3/

    Html:

    <div class="arrow-md arrow-down">
        <label for="usr">Name:</label>
        <input type="text" class="form-control input-lg" id="usr">
    </div>
    

    Css:

    .arrow-down {
      position: relative;
        overflow: visible;
      width: 400px;
      min-height: 200px;
    }
    
    .arrow-down:before {
      position: absolute;
      z-index: 1;
      top: 0;
      left: 0;
      display: block;
      width: 0; 
        height: 0; 
        border-left: solid transparent;
        border-right: solid transparent;
        border-top: solid #f00;
      content: '';
    }
    
    .arrow-md.arrow-down:before {
      border-width: 200px;
    }
    
    label,
    input {
      position: relative;
      z-index: 2;
      display: block;
      max-width: 60%;
      margin: 0 auto;
    }
    
    input {
        width: 200px;
        height: 75px;
    }
    

    您可以在三角形中添加任何内容,但需要调整内容的宽度和位置。

        2
  •  0
  •   guest271314    9 年前

    你可以使用 position:absolute 设置 top 垂直放置元素的步骤

    .arrow-down {
      width: 0;
      height: 0;
      border-left: solid transparent;
      border-right: solid transparent;
      border-top: solid #f00;
      overflow: visible;
    }
    .arrow-md {
      border-width: 200px;
    }
    .arrow-down * {
      max-width: 200px;
      max-height: 75px;
      left: 100px;
      position: absolute;
      display: block;
    }
    .arrow-down input {
      top: 50px;
    }
    .arrow-down label {
      top: 25px;
    }
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <div class="arrow-md arrow-down">
      <label for="usr">Name:</label>
      <input type="text" class="form-control input-lg" id="usr">
    </div>