Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

html - Can you float to the right of a span?

In below code I want up and down to float to right of the red line but they float past it to the div.

Why is this?

#outer {
  margin-top: 50px;
  margin-left: 50px;
  width: 300px;
  border: 1px solid lightgrey;
}

.inner {
  border: 1px solid red;
  padding: 15px 80px 15px 40px;
  position: relative;
}

.up, .down {
  border: 1px solid #000;
  float: right;
}

.down {
  clear: both;
}
<div id="outer">
  <span class="inner">
    <span class="quantity">Quantity</span>
    <span class="up">up</span>
    <span class="down">down</span>
  </span>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you check the documentation you will read this:

As float implies the use of the block layout, it modifies the computed value of the display values, in some cases:

enter image description here

Which means that your floated span become block elements inside an inline element that breaks your layout.

You can also notice that padding-top/padding-bottom and border-top/border-bottom doesn't affect the height of the outer div. This is because only the line-height is used when calculating the height of the line boxref; thus the height of the outer div is equal to the height of the line box. (you may increase the line-height to see the difference)

In order to fix both issues, you can change the display of the .inner span to inline-block:

#outer {
  margin-top: 50px;
  margin-left: 50px;
  width: 300px;
  border: 1px solid lightgrey;
}

.inner {
  border: 1px solid red;
  padding: 15px 0 15px 40px; /*remove padding-right to have them close to the red line*/ 
  position: relative;
  display:inline-block;
}

.up, .down {
  border: 1px solid #000;
  float: right;
}

.down {
  clear: both;
}
<div id="outer">
  <span class="inner">
    <span class="quantity">Quantity</span>
    <span class="up">up</span>
    <span class="down">down</span>
  </span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...