响应方块取决于内容宽度

时间:2016-02-12 15:50:07

标签: css

#wrapper 应该是一个宽度为 #text 的正方形。较长的文字应该会产生更大的正方形。换行是不必要的。这在CSS中如何工作?如果需要,可以修改HTML。

http://codepen.io/anon/pen/XXOjJB

{{1}}

这应该是这样的:

Goal

2 个答案:

答案 0 :(得分:3)

.wrapper-outer {
  display: inline-block; /* make as wide as text */
  vertical-align: top;
  background-color: green;
}

.wrapper-outer:nth-child(2) {
  background-color: tomato;
}

.wrapper-outer:nth-child(3) {
  background-color: goldenrod;
}

.wrapper-inner {
  height: 0; /* collapse the element */
  padding: 50% 20px; /* top and bottom padding equal to half the width of parent; this gives us a height equal to the width of the parent */
}

.text {
  transform: translateY(-50%); /* move text up to center; */
}
<div class="wrapper-outer">
  <div class="wrapper-inner">
    <div class="text">Lorem ipsum!</div>
  </div>
</div>

<div class="wrapper-outer">
  <div class="wrapper-inner">
    <div class="text">A</div>
  </div>
</div>

<div class="wrapper-outer">
  <div class="wrapper-inner">
    <div class="text">Lorem ipsum! Lorem ipsum! Lorem ipsum! Lorem ipsum!</div>
  </div>
</div>

答案 1 :(得分:0)

在包装器的子项中设置填充

#text {
    background-color: red;
    display: inline-block;
    padding-bottom: 50%;
    padding-top: 35%;
}

检查:https://jsfiddle.net/dLs9sj5y/