根据元素宽度更改浮动值

时间:2016-07-20 10:01:22

标签: html css

我有2个具有流体宽度并相互浮动的元素。一个元素位于左侧,另一个元素位于右侧。 当没有足够的空间时,第二个元素会断开到下一行。 如果发生这种情况,我希望它不是正确的对齐(浮动:右),而是保持对齐。



ul {
  width: 250px;
  background: #ccc;
  display: block;
  margin-bottom: 2em;
  clear: both;
  padding: 0;
  list-style: inside none;
}
.left {
  float: left;
  background: #2FCC71;
}
.right {
  float: right;
  background: #3598DC;
}
/* just for clearing floats */

ul:before,
ul:after {
  content: "";
  display: table;
}
ul:after {
  clear: both;
}

<h2>short right element</h2>
<ul>
  <li class="left">Left Element</li>
  <li class="right">Right Element</li>
</ul>
<h2>Problem: long right element is right aligned</h2>
<ul>
  <li class="left">Left Element</li>
  <li class="right">Right Element with longer text</li>
</ul>
<h2>what I would love: if right aligned element breaks, make it left aligned:</h2>
<ul>
  <li class="left">Left Element</li>
  <li class="right" style="float:left">Right Element with longer text</li>
</ul>
&#13;
&#13;
&#13;

enter image description here

3 个答案:

答案 0 :(得分:2)

Flexbox可以通过white-space:nowrap来实现这一目标。

Codepen Demo

&#13;
&#13;
* {
  margin: 0;
}
.wrap {
  width: 50%;
  margin: 1em auto;
  border: 1px solid grey;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.left {
  background: orange;
  white-space: nowrap;
}
.right {
  background: #c0ffee;
  white-space: nowrap;
}
.wrap.smaller {
  width: 40%;
}
&#13;
<div class="wrap">
  <p class="left">Short Text</p>
  <p class="right">Much longer non-breaking text</p>
</div>

<div class="wrap smaller">
  <p class="left">Short Text</p>
  <p class="right">Much longer non-breaking text</p>
</div>
&#13;
&#13;
&#13;

要了解更多信息,请在CSS-Tricks

上查看整个视频

答案 1 :(得分:0)

您可以使用媒体查询来修复

@media screen and (max-width: 480px) {  /* Put breaking size here like 480 */
     .right {
         float:left;
      }
  }

答案 2 :(得分:0)

你也可以玩jQuery

var rightText = $(".right").outerWidth();
var leftText = $(".left").outerWidth();
var ulWidth  = $("ul").width();
if((rightText+leftText) > ulWidth)
	$(".right").css("float", "left");
ul {width:250px; background:#ccc; display:block; margin-bottom:2em; clear:both;padding:0; list-style:inside none;}

	
.left {float:left; background:#2FCC71;}
.right {float:right; background:#3598DC;}

/* just for clearing floatt */
ul:before,
	ul:after {
		content:"";
		display:table;
	}
	ul:after {
		clear:both;
	}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<h2>Problem: long right element is right aligned</h2>
<ul>
  <li class="left">Left Element</li>
  <li class="right">Right Element with longer text</li>
</ul>

相关问题