Ricardo Marques
Ricardo Marques

Reputation: 99

Using only CSS, can I limit a child to the parent width, without previously fixing the parent's width?

This is my first question so I'll try my best to get my point across as coherently as I can.

Lets assume something like:

<div id="parent">
    <div id="child1">shot text</div>
    <div id="child2">very long text</div>
</div

What I'm asking is is there a way to "link/lock" #child2 width to #child1's width or #parent's so that #child2 never exceeds #child1's width.

Is there anyway, using only CSS, I can force #child2 (or #parent) to have the same width as #child1, without fixing #parent's and #child1's width?

The point is that I want to be able to edit the contents on the fly (like translations) of both #child1 and #child2 but as #child2 will always have more words it will always be wider.

PS: Don't forget, using only CSS, no JavaScript.

Edit: Done a fiddle https://jsfiddle.net/ricardojcmarques/seckdugj/5/

Basically what I need is the green box to be the same width as the orange box, without giving the orange box (nor the brown) any width. Using the width the browser needed to render it correctly.

Upvotes: 3

Views: 1209

Answers (2)

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13908

So just Improvised on your suggestion, the key here is to set

#parent{
    background: brown;
    position: absolute;
    left: 0;
    height: 0;
    margin: 0;
    padding: 0;
}

Heres is a working JSfiddle

Upvotes: 1

Kinburn101
Kinburn101

Reputation: 1162

DEMO

A little bit of a hack but it might work.

<div id="parent">
<div id="child1">short text that will expand and expand
<div id="child2">very long text that will remain within the confines of child1
</div>
</div>
</div>

#parent {
position:absolute;
background-color:green;
padding:5px;
padding-bottom:0;
}
#child1 {
position:relative;
background-color:#fff;
}
#child2 {
position:absolute;
border:5px solid green;
border-top:none;
margin-left:-5px;
margin-right:-5px;
}

EDIT

Have a look at this one, it's a little closer to yours but I have to modify the list in order to nest child2. I don't know if you have a specific style you need to set to the parent div but if you do it will take some more thought. Demo2

Upvotes: 0

Related Questions