dimlucas dimlucas - 5 months ago 19
CSS Question

Fully circular buttons with dynamic size

I am trying to create circular buttons in CSS. I use

border-radius: 100%
to make the button look like a circle but it only works if I explicitly set the width and height of the element. But if I do so, the buttons will not adjust to fix larger text

This is what I've tried so far:



.round-button{
width: 60px;
height: 60px;
text-decoration: none;
display: inline-block;
outline: none;
cursor: pointer;
border-style: none;
color: white;
background-color: #3498db;
border-radius: 100%;
overflow: none;
text-align: center;
}

.round-button:active{
background-color: #2980b9;
}

<div>
<button class="round-button">Button</button>
</div>
<div>
<button class="round-button">This text will overflow the button!</button>
</div>





As you can see the first button looks pretty OK, but the text in the second button overflows it. I've used
overflow: hidden
to prevent it from looking ugly but I would like the buttons size to adjust according to the content's size. Is that possible?

Answer

In order to draw a circle, you need a square to start with .

You can insert a pseudo of an height equal to width using vertical padding with percentage value.

https://www.w3.org/TR/CSS2/box.html#padding-properties The percentage is calculated with respect to the width of the generated box's containing block, even for 'padding-top' and 'padding-bottom'. If the containing block's width depends on this element, then the resulting layout is undefined in CSS 2.1.

Unlike margin properties, values for padding values cannot be negative. Like margin properties, percentage values for padding properties refer to the width of the generated box's containing block.

Make this pseudo inline-block to help yoy center text.

If text has to wrap a few lines, it needs to be wraped within an inline-block .. if you use an inline-block pseudo.

You can set max and min width too.

example:

.round-button{
  min-width: 60px;
  max-width:120px;
  text-decoration: none;
  display: inline-block;
  outline: none;
  cursor: pointer;
  border-style: none;
  color: white;
  background-color: #3498db;
  border-radius: 100%;
  overflow: none;
  text-align: center;
  padding:0;
}
.round-button:before {
  content:'';
  display:inline-block;;
  vertical-align:middle;
  padding-top:100%;
}
span {
  display:inline-block;
  vertical-align:middle;
  max-width:90%;
}
.round-button:active{
  background-color: #2980b9;
}
<div>
  <button class="round-button"><span>Button</span></button>
</div>
<div>
  <button class="round-button"><span>This text should NOT overflow the button!</span></button>  
</div>

Comments