CSS PX to Percentage [closed]
Asked Answered
C

3

10

Ok so this question seems to have been asked a fair few times but still haven't managed to get the plain simple answer I'm after from looking at others questions so will ask this my own way. I'm wanting to create a site with a container in CSS as follows:

.container {
     height: 100%;
     margin: 0 auto;
     width: 980px;
}

However for the width I'm wanting to use a percentage but for the life of me I cannot find one simple answer or even a site that converts PX to % or even just to get an answer to what percentage is used in place of 980px or 960px ? Is it 62.5% or 70% ?

Could someone please help me out with this and answer this simple question or at least give me a site that I can look at with conversions and just before anyone answers with PX to EM site, I've already looked at it and it's not clear as that site is more for font sizes.

Thank you to anyone who can answer this!

Curtal answered 20/3, 2014 at 1:6 Comment(2)
everone uses their own screen resolutions. Percent is taken depening on the parent, which is the screen resolution in this scenario. You can set you wrapper to 980px and then use percent in it for child elements, but that's about it.Allmon
Check out this: pastebin.com/raw/qfHvRAYaBasiliabasilian
K
29

I hate to break it to you, but you're likely to have a few people rolling their eyes at you here.

A percentage is relative to whatever the parent container's size is. 50% means "half of the width of the parent". There is no "px-%" conversion, because one is a fixed value and the other is a flexible ratio. That's... kinda why you can't find any such thing.

Kb answered 20/3, 2014 at 1:8 Comment(2)
but what is this? nekocalc.com/px-to-percentage-converter i dont understand this converterOdysseus
Completely meaningless. By default (which is editable) it assumes that 16px = 100% and gives you ratios accordingly.Kb
B
14

Problem: To get child element in percent,

  1. A) Child width: eg. 760px
  2. B) Parent width : eg. 1024px

You can get parent or child width easily with JQuery. eg: $('#parent').width()

Then apply this Mathematical operation to get the percentage value of child element:
(A / B) * 100

Substituting :
(760/1024) * 100 = 74.22% .. hence solved.

Boatwright answered 15/2, 2016 at 17:56 Comment(0)
V
1

Instead of converting from pixel to percentage try to get the dimension of your element in percentage example

var width = $('#someElt').width();
var parentWidth = $('#someElt').offsetParent().width();
var percent = 100*width/parentWidth;
Vanthe answered 14/2, 2019 at 4:59 Comment(1)
good suggestion to do it programatically.Toothache

© 2022 - 2024 — McMap. All rights reserved.