Подтвердить что ты не робот

Альтернатива CSS Calc

Я пытаюсь динамически изменять ширину div с помощью CSS и без jquery. Следующий код будет работать в следующих браузерах: http://caniuse.com/calc

/* Firefox */
width: -moz-calc(100% - 500px);
/* WebKit */
width: -webkit-calc(100% - 500px);
/* Opera */
width: -o-calc(100% - 500px);
/* Standard */
width: calc(100% - 500px);

Я хочу также поддерживать IE 5.5 и выше, я нашел следующее: выражение. Это правильное использование:

/* IE-OLD */
width: expression(100% - 500px);

Могу ли я также поддерживать браузер Opera и Android?

4b9b3361

Ответ 1

Почти всегда box-sizing: border-box может заменить правило calc, такое как calc(100% - 500px), используемое для компоновки.

Например:

Если у меня есть следующая разметка:

<div class="sideBar">sideBar</div>
<div class="content">content</div>

Вместо этого: (Предполагая, что боковая панель шириной 300 пикселей)

.content {
  width: calc(100% - 300px);
}

Сделайте это:

.sideBar {
     position: absolute; 
     top:0;
     left:0;
     width: 300px;
}
.content {
    padding-left: 300px;
    width: 100%;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

* {
  margin: 0;
  padding: 0;
}
html,
body,
div {
  height: 100%;
}
.sideBar {
  position: absolute;
  top: 0;
  left: 0;
  width: 300px;
  background: orange;
}
.content {
  padding-left: 300px;
  width: 100%;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: wheat;
}
<div class="sideBar">sideBar</div>
<div class="content">content</div>

Ответ 2

Просто сделайте резерв перед тем, как Calc сделает трюк.

width: 98%;               /* fallback for browsers without support for calc() */
width: calc(100% - 1em);

Подробнее здесь https://developer.mozilla.org/en-US/docs/Web/CSS/calc

Ответ 3

используйте этот

    .content
{
    width: 100%;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding-right: 500px;
    margin-right: -500px;
}

Ответ 4

Просто потратил большую часть 3 часов, пытаясь обойти это для конкретного случая на устройствах andriod, не смог получить размер коробки, чтобы работать, поэтому я связал его с моим JS как грязным обходным решением... не нужно jQuery!:)

Взято за рабочий код на andriod 2.3.

<div class="sessionDiv" style="width:auto;">
<img> <!-- image to resize -->
</div>
<div class="sessionDiv" style="width:auto;">
<img> <!-- image to resize -->
</div>

JS с прослушивателями событий

var orient =
{
    orientation:window.orientation,
    width: window.innerWidth,
    check: function()
    {
        // if orientation does not match stored value, update
        if(window.orientation !== this.orientation)  
        {
            this.orientation = window.orientation; //set new orientation
            this.width = window.innerWidth; //set new width
            this.adjustIrritatingCSS(this.width); //change ui to current value
        }
        //if width does not match stored value, update
        if(window.innerWidth !== this.width)
        {
            this.width = window.innerWidth; //set new width
            this.adjustIrritatingCSS(this.width); //change ui to current value
        }
    },
    adjustIrritatingCSS: function(screenWidth)
    {   
    //disgusting workaround function
        var titleBoxes = document.getElementsByClassName('sessionDiv'); 
        var i = titleBoxes.length;
        var sessWidth = screenWidth - 300; // calc(100% - 300px); -> equivalent
        while(i--)
        {
            titleBoxes[i].style.width = String( sessWidth + "px"); 
            //resize image in auto sized div
        }
        sessWidth = null; //clear width
        titleBoxes = null; //clear nodelist
        i = null; // clear index int
    }
};

window.onload = function()
{
    window.addEventListener('resize', function(){orient.check();}); 
    //on resize, check our values for updates and if theres changes run functions
    window.addEventListener('orientationchange', function(){orient.check();});
    //on rotate, check our values for updates and if theres changes run functions
    setInterval(function(){orient.check();}, 2000);
    //occasionally check our values for updates and if theres changes run functions(just incase!!)
    orient.adjustIrritatingCSS(orient.width); 
    //sets value on first run
};

Надеюсь, это поможет любому, кто не может получить размер коробки! PS У меня возникли проблемы с ios, используя это...

Ответ 5

Измените ширину #menuLog с% или px, и вы увидите магию. Работает с каждым устройством даже < 2.3

*{
	-moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
#menuLog{
  width:30%;
  /*width:300px;*/
	height: 60px;
	padding: 5px;
	background-color: #ddd;
}
#menuLog > div[inline-log="1"]{
	display: inline-block;
	vertical-align: top;
	width: 100%;
	height: 100%;
	margin-right: -60px;
}
#menuLog > div[inline-log="1"] > div[inline-log="1.1"]{
	margin-right: 60px;
	height: 100%;
	background-color: red;
}
#menuLog > div[inline-log="2"]{
	display: inline-block;
	vertical-align: top;
	width: 60px;
	height: 100%;
}
#menuLog > div[inline-log="2"] > div[inline-log="2.1"]{
	display: inline-block;
	vertical-align: top;
	width: 55px;
	height: 100%;
	background-color: yellow;
	margin-left:5px;
}
<div id="menuLog">
  <div inline-log="1">
    <div inline-log="1.1">
      One
    </div>
  </div><div inline-log="2">
     <div inline-log="2.1">
      Two
     </div>
  </div>
</div>

Ответ 6

Я хотел добавить альтернативу no-calc, no-border-box (т.е. CSS2).

Элементы блока нормального потока изначально имеют width: auto, который фактически представляет собой ширину содержащего блока за вычетом ширины поля, границы и заполнения.

Пример выше может быть выполнен без рамки, просто как

.content {
    padding-left: 300px;
}

Аналогично, при

.content {
  margin-left: 1px;
  border-left: 1em solid;
  padding-left: 1rem;
}

эффективная ширина 100% - 1px - 1em - 1rem.

Для абсолютно позиционированных элементов height: auto имеет схожие свойства:

.content {
  position: absolute;
  top: 0;
  bottom: 0;
  margin-bottom: 1px;
  border-bottom: 1em solid;
  padding-bottom: 1rem;
}

Здесь эффективная высота 100% - 1px - 1em - 1rem.