简体   繁体   中英

What is the best way to float elements of the same class side by side?

HTML/CSS beginner here, trying to figure out the best way to do things. Ideally it would be nice to have an explanation as well as a solution.

So what I'm trying to do is placing several buttons (maybe 5-6) side by side, followed by a label

The buttons are formatted using the same CSS class. To place them side by side, I am setting float: left;

Unfortunately, this places the next element after the buttons (the label) on the same line as well, even if I set clear: both; for the label.

The problem is that float: left; governs how other elements format around the given element. This is great for the first n-1 buttons since it places the next button to the side of it. But it also places the label next to the last button.

Is there a way to fix this behavior without having to add specific CSS formatting to the last button, or provide a specific width which forces the label to be on the next line? (like maybe a different method of doing this altogether?)

This is a sample of what I'm doing now:

<style>
  .myButton {
    float: left;
  }
  #myLabel {
    clear: both;
  }
</style>
<div>
  <button class="myButton">Button 1</button>
  <button class="myButton">Button 2</button>
  <button class="myButton">Button 3</button>
  <button class="myButton">Button 4</button>
  <label id="myLabel">Output Text</label>
</div>

Thanks

label is, by default, an inline element. clear however only works on block-level elements , which makes sense.

You would have to wrap the buttons in a separate element, and/or apply display:block to the label.

You don't need to float your buttons; they will naturally flow next to each other the same as text (kinda). If you want to put the label on its own line, you have a couple options:

  1. Put a line break ( <br /> ) in the html between the last button and the label
  2. Make your label display: block; in the CSS, which will ensure that it's the only thing on its line (after the floats are gone)

Please check this: jsFiddle . I basically wrapped the buttons in a <div id="buttons"> and assigned the following styles to that <div> .

#buttons {
    width: 100%;
    overflow: hidden;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM