How do I keep text from wrapping under an element which floats to its left?

喜夏-厌秋 提交于 2019-12-13 06:06:55

问题


I have two block elements. The first is floated to the left. I'd expect the right element to be a block as well and retain its square shape. Instead, text within it is wrapping under the element which is floating to the left.

CSS:

.comment-date { 
    float: left;     
}

HTML:

<div class="comment-date">07/08 23:08</div>
<div class="comment-body">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
    sed do eiusmod tempor incididunt ut labore et dolore magna 
    aliqua. Ut enim ad minim veniam, quis nostrud exercitation.
</div>

The lorem ipsum text wraps under the date. I'd expect it to retain a block shape, floating to the right of the date. How can I achieve that?

Here is a fiddle: http://jsfiddle.net/CS2Hs/


回答1:


An alternative to the other solutions here would be to simply add a margin-left to .comment-body. It would also be helpful to apply a set width to .comment-date

.comment-date { 
  float: left;     
  font-weight: bold;    
  width: 90px;
}
.comment-body {
  margin-left: 90px;
}

This will ensure that the text in .comment-body does not appear underneath the date.

Here is a demo:

--- jsFiddle DEMO ---




回答2:


The body block is not in the float model. Simply set a float: left for .comment-body too. Also, you could use some widths. See: http://jsfiddle.net/CS2Hs/3/




回答3:


I will try to understand your problem. As I understand, you want the .comment-body to be on the right and the .comment-date to be on the left but on the same line.

If I am right, maybe this will works:

.comment-date {
    display: inline-block;
    float: left;
    width: 15%;
    font-weight: bold;
}
.comment-body {
    display: inline-block;
    float: right;
    width: 85%;
}

I made a JSFiddle just for you ;)




回答4:


jsfiddle appears to be down at the moment so sorry if this doesn't work/isn't what you wanted but have you tried adding "overflow:hidden" to "comment-body"? This creates a new layout context which stops the text from wrapping underneath. I find this amazingly useful! Hope that helps!



来源:https://stackoverflow.com/questions/11979556/how-do-i-keep-text-from-wrapping-under-an-element-which-floats-to-its-left

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!