Граница, позиция и заполнение не работают, когда отображается: установлен inline. также странное поведение с относительной позиции - PullRequest
8 голосов
/ 09 января 2012

У меня есть два класса CSS:

.class1 {
    height: 100%;
    width: 300px;
    border: 1px none #B0B0B0;
    position: relative;
    display: inline;
    left: 10px;
}
.class2 {
    height: 100%;
    width: 200px;
    position: relative;
    display: inline;
    margin-left: 15px;
    background-color: #00CCCC;
    border-top-width: 1px;
    border-right-width: 1px;
    border-bottom-width: 1px;
    border-left-width: 1px;
    border-top-style: solid;
    border-right-style: solid;
    border-bottom-style: solid;
    border-left-style: solid;
}

Теперь, как вы можете видеть, они оба настроены на отображение в строке (без разрывов строк между элементами). Который работает правильно. Но по какой-то причине, с тех пор, как я установил отображение в линию, Padding, Positioning и Margin CSS перестали работать. Я могу добавить на полях 10 дюймов, и ничего не произойдет. То же самое с отступами и позиционированием.

Может кто-нибудь объяснить, как это исправить?

Кроме того, у меня установлена ​​относительная позиция для обоих классов, но при просмотре страницы в браузере .class2 за кругом .class1, когда предполагается, что она находится сразу после .class1.

Есть идеи?

EDIT

Ладно, я сделал JSFiddle, но там, кажется, он играет еще больше ...

Похоже, Width не работает ....

вот оно:

http://jsfiddle.net/zYbwh/1/

Ответы [ 3 ]

8 голосов
/ 09 января 2012

Вам нужно использовать

display: inline-block;

вместо этого. margin не работает с display: inline элементами, однако с inline-block это работает. Затем вы можете иметь встроенный элемент с полями и явной шириной / высотой.

Чтобы это работало в IE7, добавьте две строки:

*display: inline;
zoom: 1;

Это ужасно, но работает.

0 голосов
/ 03 апреля 2015

Это проблема, с которой вы сталкиваетесь при использовании шаблонов, я запрограммировал сайт на php, но дизайн убивает меня.Так что я попробовал немного ракетного топлива для веб-дизайнеров.

И это проблемы, которые я продолжаю получать на каждом шагу ... Встроенный блок не работает для меня, ничего не работает, потому что это не моедизайн, и я не знаю настройки.

Я пытаюсь сделать дизайн сам, но у меня нет времени, мне нужен дизайн вчера.

Я предлагаю вам взять то, что вам нужно из шаблонови удалите все остальное, что уменьшит вашу проблему и сэкономит ваше время.

0 голосов
/ 29 мая 2013

Я знаю, что это довольно поздний ответ, но я написал плагин jQuery, который поддерживает заполнение встроенных элементов (с разрывом слов), см. Этот JSfiddle:

http://jsfiddle.net/RxKek/

Код плагина:

$.fn.outerHTML = function () {
// IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
return (!this.length) ? this : (this[0].outerHTML || (
    function (el) {
        var div = document.createElement('div');
        div.appendChild(el.cloneNode(true));
        var contents = div.innerHTML;
        div = null;
        return contents;
    })(this[0]));

};

/*
Requirements:

1. The container must NOT have a width!
2. The element needs to be formatted like this:

<div>text</div>

in stead of this:

<div>
    text
</div>
*/

$.fn.fixInlineText = function (opt) {
return this.each(function () {
    //First get the container width
    var maxWidth = opt.width;

    //Then get the width of the inline element
    //To calculate the correct width the element needs to 
    //be 100% visible that's why we make it absolute first.
    //We also do this to the container.
    $(this).css("position", "absolute");
    $(this).parent().css("position", "absolute").css("width", "200%");

    var width = $(this).width();

    $(this).css("position", "");
    $(this).parent().css("position", "").css("width", "");

    //Don't do anything if it fits
    if (width < maxWidth) {
        return;
    }

    //Check how many times the container fits within the box
    var times = Math.ceil(width / maxWidth);

    //Function for cleaning chunks
    var cleanChunk = function (chunk) {
        var thisChunkLength = chunk.length - 1;

        if (chunk[0] == " ") chunk = chunk.substring(1);
        if (chunk[thisChunkLength] == " ") chunk = chunk.substring(0, thisChunkLength);

        return chunk;
    };

    //Divide the text into chunks
    var text = $(this).html();
    var textArr = text.split(" ");

    var chunkLength = Math.ceil((textArr.length - 1) / times);
    var chunks = [];

    var curChunk = "";
    var curChunkCount = 0;

    var isParsingHtml = false;

    //Loop through the text array and split it into chunks
    for (var i in textArr) {
        //When we are parsing HTML we don't want to count the
        //spaces since the user doesn't see it.
        if (isParsingHtml) {
            //Check for a HTML end tag
            if (/<\/[a-zA-Z]*>/.test(textArr[i]) || /[a-zA-Z]*>/.test(textArr[i])) {
                isParsingHtml = false;
            }
        } else {
            //Check for a HTML begin tag
            if (/<[a-zA-Z]*/.test(textArr[i])) {
                isParsingHtml = true;
            }
        }

        //Calculate chunks
        if (curChunkCount == (chunkLength - 1) && !isParsingHtml) {
            curChunk += textArr[i] + " ";
            chunks.push(cleanChunk(curChunk));
            curChunk = "";
            curChunkCount = -1;
        } else if ((i == (textArr.length - 1))) {
            curChunk += textArr[i];
            chunks.push(cleanChunk(curChunk));
            break;
        } else {
            curChunk += textArr[i] + " ";
        }

        if (!isParsingHtml) {
            curChunkCount++;
        }
    }

    //Convert chunks to new elements
    var el = $($(this).html("").outerHTML());

    for (var x in chunks) {
        var new_el = el.clone().html(chunks[x]).addClass("text-render-el");
        var new_el_container = $("<div/>").addClass("text-render-container");

        new_el_container.append(new_el);

        $(this).before(new_el_container);
    }

    //Finally remove the current element
    $(this).remove();
});

};

...