Boostrap: How to “stick” a button over an image when re-sizing

后端 未结 2 1680
既然无缘
既然无缘 2020-12-29 00:50

I have an image in which I need to put a button over, the problem is that I don\'t know how to place the button and automatically re-size and position it when making the bro

相关标签:
2条回答
  • 2020-12-29 01:12

    I have to ask if there's a possibility to replace form tag into another DIV? Then you can just use position: absolute for button. I created fiddle to show how https://jsfiddle.net/1x1pjwk7/

    0 讨论(0)
  • 2020-12-29 01:35

    Ah, the good old "how to overlay stuff on top of a responsive image -- responsively" question.

    A little tricky, but not too bad. The tricky bit is how to make the stuff's vertical position responsive when the image size changes.

    Fear not, here's one simple way to do this:

    HTML:

    <div class="img-wrapper">
        <img class="img-responsive" src="http://lorempixel.com/output/people-q-c-1200-400-4.jpg">
        <div class="img-overlay">
          <button class="btn btn-md btn-success">Button</button>
        </div>
    </div>
    

    CSS:

    .img-wrapper {
      position: relative;
     }
    
    .img-responsive {
      width: 100%;
      height: auto;
    }
    
    .img-overlay {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      text-align: center;
    }
    
    .img-overlay:before {
      content: ' ';
      display: block;
      /* adjust 'height' to position overlay content vertically */
      height: 50%;
    }
    

    The img-overlay:before pseudo-class handles the vertical positioning job by pushing the img-overlay div down from the top of the image. In this example, the top of the button will always be 50% down the image (change the height: 50% attribute if you want the button higher or lower).

    jsfiddle

    To make the button size responsive to window width, you can create a new class for your button. Let's call it btn-responsive (this replaces btn-md in the example above). Then use @media queries to adjust the btn-responsive attributes for different window widths. Something like this:

    .btn-responsive {
      /* matches 'btn-md' */
      padding: 10px 16px;
      font-size: 18px;
      line-height: 1.3333333;
      border-radius: 6px;
    }
    
    @media (max-width:760px) { 
        /* matches 'btn-xs' */
        .btn-responsive {
            padding: 1px 5px;
            font-size: 12px;
            line-height: 1.5;
            border-radius: 3px;
        }
    }
    

    and so forth for other screen widths.

    0 讨论(0)
提交回复
热议问题