François M.
François M.

Reputation: 4278

Setting the height of a button as a % of the window

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.

Upvotes: 1

Views: 764

Answers (4)

Lordbalmon
Lordbalmon

Reputation: 1714

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

Upvotes: 3

rnevius
rnevius

Reputation: 27112

You can use viewport units:

#mybutton {
    height: 10vh;
}

Viewport-relative lengths are supported by all modern browsers.

Upvotes: 5

dpedoneze
dpedoneze

Reputation: 959

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).

Upvotes: 2

jameshwart lopez
jameshwart lopez

Reputation: 3151

Try putting a !important

#mybutton {
    height: 10% !important;
}

Upvotes: -3

Related Questions