如何避免使用JS并仅使用CSS?

时间:2017-03-31 08:34:04

标签: javascript jquery html css

经过几次测试,我无法用纯粹的CSS做我想做的事情。如何在不使用javascript的情况下获得与下面示例相同的结果。

是否可以使用纯CSS进行此操作?

感谢。

jsfiddle Demo



var main = document.getElementsByClassName('container');
for(var i = 0; i < main.length; i++) {	
	var height = main[i].childNodes[3].offsetHeight;
	main[i].style.height = height+"px";
}
&#13;
.container {
  width: 100%;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}
&#13;
<div class="container">
  <div class="left-child">
  </div>  
  <div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

喜欢这个吗?

我已将height添加到.container,因为孩子们绝对定位,他们不在文档的流程中,这意味着它就像.container那样&n&n根本没有孩子。

对于height:100%的{​​{1}},它是这样的,它取得了最近的相对定位元素的高度,即.right-child

&#13;
&#13;
.container
&#13;
.container {
  width: 100%;
  height: 200px;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 100%;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以使用flexbox执行此操作,只需将display: flex;align-items: center;添加到.container

并移除position: absolutetransform translate内容并获得干净的CSS

.container {
  background: yellow;
  margin-bottom: 10px;
  display: flex;             /* added property */
  align-items: center;       /* added property */
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
}
<div class="container">
  <div class="left-child">
  </div>  
  <div class="right-child">
  </div>
</div>

<div class="container">
  <div class="left-child">
  </div>
  <div class="right-child">
  </div>
</div>

答案 2 :(得分:1)

另一种方式:

.container {
  width: 100%;
  background: yellow;
  overflow:hidden;
  margin-bottom: 10px;
}
.left-child {
  margin-top:30px;
  width: 40%;
  height: 120px;
  background: red;
  float:left;
}
.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  float:right;
}

https://jsfiddle.net/ghdzy57w/14/

答案 3 :(得分:1)

没有a2()position : relative

的解决方案

&#13;
&#13;
position : absolute
&#13;
.container {
  width: 100%;
  background: yellow;
  margin-bottom: 10px;
  display: inline-block;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  margin-top: 30px;
  display:inline-block;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  display:inline-block;
  float: right;
}
&#13;
&#13;
&#13;