Break letters of second child div

后端 未结 6 1167
臣服心动
臣服心动 2021-01-12 16:24

I have one requirement, where I need to apply width to the parent element which is equal to the first child element\'s width. This can be easily achieved using display

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 17:02

    Ideally, the layout style for a HTML snippet like:

    first
    firstvaluevalue
    second value value
    third valuevalue
    valuevalue on the fourth line

    is achievable using the following CSS:

    .main {
        display: inline-block;
        background-color: cornflowerblue;
        position: relative;
        width: 50px;
    }
    .first {
        width: 50px; /* I don't know this width */
        height: 50px; /* I don't know this height */
        background-color: grey;
    }
    .value {
        word-break: break-all;
        margin: 1.00em 0;
    }
    

    as shown in: http://jsfiddle.net/audetwebdesign/tPjem/

    However, I had to set the width of .main to that of the .first element in order to get the word-break property to take effect.

    The CSS rendering problem here is that you want the width of the .value siblings to be equal to the unknown width of .first, which cannot be done with CSS alone.

    CSS rendering is essentially a one-pass top-to-bottom algorithm which means that parent elements cannot inherit values from child elements (tables have a multi-pass algorithm but this won't help in this case). This may change in future versions of CSS, but for the we need to design according to these limitations.

    The JavaScript/jQuery solution is to get the width from .first and apply it to .main and bind that to a window re-size action.

    In some ways, this problem seems to make sense if .first contains an image which would have an intrinsic height and width. If this were the case, it might make sense to set the width of .main to a reasonable value and then scale the image in .first to fill the width of the .main block.

    Without knowing more about the actual content, it is hard to come up with alternatives.

提交回复
热议问题