How to responsively indent an element

I have some text I want to indent by a certain amount, let's say 20px. However, the length of the text is dynamic. If the width of the text is less than the screen width, but the text + 20px is greater than the screen width, I do not want the text to go to the next line. Rather I would like to reduce the indentation.

These are the cases I would like to accommodate:

Short text:

| Lorem ipsum |

Text < screen-width, but text+20px > screen-width:

| Lorem ipsum dolors amet|

Text = screen-width:

|Lorem ipsum dolor sit amet|

Text > screen-width:

|Lorem ipsum dolor sit amet|
|consectetuer adipiscing. |

I know this is a bit silly and it really isn't that important. But it was frustrating me that I couldn't figure out how to do it.


Here's a CSS-only solution... works for browsers that support calc .

<div class="indent">
    <span>Lorem ipsum dolor sit amet consectetuer adipiscing.</span>
</div>
.indent {background:pink;}
.indent span {float:right; min-width:calc(100% - 20px);}
.indent:after {content:""; display:table; clear:both;}

Fiddle: http://jsfiddle.net/anwPa/


http://jsfiddle.net/qm92C/1/

In this example I used a little jQuery to test each paragraph element against the width of the screen - 20px. If that condition is met, the text-indent is removed. Otherwise, it's left the same.

$(function(){
    $("p").each(function(){
        if ($(this).width() > ($(window).width() - 20)){
            $(this).css("text-indent",0);
        };
    });
});

The only downside is that in order to test the width of the paragraphs, I had to change them to inline-block level elements as opposed to block level elements.


Use CSS media queries to set specific CSS rules based on the width of the user device. http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

链接地址: http://www.djcxy.com/p/75540.html

上一篇: 将输入与具有背景图像的标签垂直对齐

下一篇: 如何响应地缩进元素