1

I'm trying to set the height of a button as a % of the user's window. It seems this works :

#mybutton {
    padding: 10%;
}

But obviously doesn't quite achieve what I need (in addition, it's not responsive to the browser's size).

This doesn't work :

#mybutton {
    height: 10%;
}

I've also tried doing it with javascript (I really don't master it), but none of those two tries work either.

document.getElementById('mybutton').style.height = "10%";
document.getElementById('mybutton').style.height = window.outerHeight / 10;

How can I do that ?

PS : I've also tried with fixed values (100px) to see if I could change the height, and it seems I can't at all.

NB : I'd like it to be responsive to the user's window, meaning that if I reduce the size of my browser, the button should keep a height of 10% of it.

Thanks.

François M.
  • 4,027
  • 11
  • 30
  • 81

4 Answers4

5

You can use viewport units:

#mybutton {
    height: 10vh;
}

Viewport-relative lengths are supported by all modern browsers.

rnevius
  • 26,578
  • 10
  • 58
  • 86
3

Though the answer has been selected I wanted to note three things here.

Note #1

#mybutton {
    height:10%;
}

does not work because the height is relative to the parent and the parents, html and body, are not 100%. Checkout this fiddle, http://jsfiddle.net/3sLafksx/1/

Note #2

The reason padding worked is because padding is not relative to the parent's height but to the parent's width. Which in case of a div element or plainly in the body is 100% of the window size.

Refer: https://stackoverflow.com/a/8211457/1799502 and http://www.w3schools.com/cssref/pr_padding.asp

Note #3

Using the viewport height vh and viewport width vw units is a very good idea but @rnevius was not kidding when he said all modern browsers, you need at least IE9 or Android 4.4

Community
  • 1
  • 1
Lordbalmon
  • 1,634
  • 1
  • 14
  • 31
2

IF your element is a span, it won't work like you wish, but using a div, your code will work.

document.getElementById('b').style.height = (window.outerHeight / 10) + 'px';

Using css, your button will be X% of your parent container, so if you have a parent container with 300px height, your button'll be 30px height (using height: 10%).

You can also use the vh unit like @rnevius pointed out. But remember that a span won't work as you want, because it isn't a block element. (unless you force it by using display: (inline-)block).

dpedoneze
  • 949
  • 7
  • 17
  • Buttons in Bootstrap are always of the `inline-block` type...Which is why I didn't include that info in my answer. (This question was tagged with `twitter-bootstrap-3`). – rnevius Jul 31 '15 at 01:19
-3

Try putting a !important

#mybutton {
    height: 10% !important;
}
jameshwart lopez
  • 2,993
  • 6
  • 35
  • 65