首页 > 解决方案 > 如何在html5中仅使用css在容器内绘制具有四个div的矩形?

问题描述

如何从下面的代码中仅使用 css 构建矩形?

<div id='rectangle'>
    <div class='line'></div>
    <div class='line'></div>
    <div class='line'></div>
    <div class='line'></div>
  </div>

标签: htmlcss

解决方案


您可以使用以下内容。我不建议使用idfor 样式。如果由于某种原因您想要多个rectangle比并且id不是要走的路。这是因为并且id可以被视为identification一个人。意味着 anid在页面上应该是唯一的。

.rectangle {
  width: 200px;
  height: 200px;
  position: relative;
}

.line {
  position: absolute;
  background: red; 
}


.top, .bottom {
  height: 1px;
  width: 100%;
  left: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

.left, .right {
  height: 100%;
  width: 1px;
  top: 0;
}

.left {
  left: 0;
}

.right {
  right: 0;
}
<div class="rectangle">
  <div class="line top"></div>
  <div class="line right"></div>
  <div class="line bottom"></div>
  <div class="line left"></div>
</div>

或者:

.rectangle {
  border: 1px solid red;
  width: 200px;
  height: 200px;
}
<div class="rectangle"></div> 


推荐阅读