Make button width fit to the text

后端 未结 8 661
一生所求
一生所求 2020-12-29 20:29

While I was fiddling with this \'Fancy 3D Button\' example, I found that the width seemed to be hard-coded to fit the text\'s width.

Here is the HTML /

8条回答
  •  感动是毒
    2020-12-29 21:05

    Keeping the element's size relative to its content can also be done with display: inline-flex and display: table

    The centering can be done with..

    • text-align: center; on the parent (or above, it's inherited)

    • display: flex; and justify-content: center; on the parent

    • position: absolute; left: 50%; transform: translateX(-50%); on the element with position: relative; (at least) on the parent.

    Here's a flexbox guide from CSS Tricks

    Here's an article on centering from CSS Tricks.

    Keeping an element only as wide as its content..

    • Can use display: table;

    • Or inline-anything including inline-flex as used in my snippet example below.

    Keep in mind that when centering with flexbox's justify-content: center; when the text wraps the text will align left. So you will still need text-align: center; if your site is responsive and you expect lines to wrap.

    • More examples in this stack answer

    body {
      display: flex;
      flex-direction: column;
      height: 100vh;
      padding: 20px;
    }
    .container {
      display: flex;
      justify-content: center; /* center horizontally */
      align-items: center; /* center vertically */
      height: 50%;
    }
    .container.c1 {
      text-align: center; /* needed if the text wraps */
      /* text-align is inherited, it can be put on the parent or the target element */
    }
    .container.c2 {
     /* without text-align: center; */
    }
    .button {
      padding: 5px 10px;
      font-size: 30px;
      text-decoration: none;
      color: hsla(0, 0%, 90%, 1);
      background: linear-gradient(hsla(21, 85%, 51%, 1), hsla(21, 85%, 61%, 1));
      border-radius: 10px;
      box-shadow: 2px 2px 15px -5px hsla(0, 0%, 0%, 1);
    }
    .button:hover {
      background: linear-gradient(hsl(207.5, 84.8%, 51%), hsla(207, 84%, 62%, 1));
      transition: all 0.2s linear;
    }
    .button.b1 {
        display: inline-flex; /* element only as wide as content */
    }
    .button.b2 {
        display: table; /* element only as wide as content */
    }
    
    

    Fiddle

    https://jsfiddle.net/Hastig/02fbs3pv/

提交回复
热议问题