in my website i have FAQ page which the users can add questions and images
<div class="FAQ container">
<div class="content">text text text</div>
<div class="pic"><img></div>
</div>
if the user adds only text to the question then div .class should be 100% width if the user adds text and img the 2 divs should be 50% each, next to each other, how can i do it?
I'm going to assume you are using a database like MySQL. I'm also going to assume that your your database query returns the following fields question, answer and _image_path_.
PHP
$faq_html = '<div class="faq %s"><div class="content">Q: %s<br>A: %s</div>%s</div>';
while ( $row = $result->fetch_object() ) :
$container_class = 'no-image';
$faq_img_html = '';
if ( ! empty( $row->image_path ) ) :
$container_class = 'has-image';
$faq_img_html = sprintf( '<div class="pic"><img src="%s" /></div>', $row->image_path );
endif;
$faqs .= sprintf( $faq_html, $container_class, $row->question, $row->answer, $faq_img_html );
endwhile;
echo '<div class="faqs-container">' . $faqs . '</div>';
The output would either have a class of .no-image
or .has-image
on a DIV wrapper for each individual FAQ.
HTML
<div class="faq no-image">
<div class="content">
Q: text text text? <br>
A: text text text
</div>
</div>
<div class="faq has-image">
<div class="content">
Q: text text text? <br>
A: text text text
</div>
<div class="pic"><img src="your-img.jpg" /></div>
</div>
Once you have that just sprinkle in a little CSS.
.no-image .content { width: 100%; }
.has-image .content,
.has-image .pic { width: 50%; }
If I understood you right, the text-Div is always filled and the Image-Div only sometimes, right? For this situation I would suggest, that you try this CSS (unchecked):
.pic{
max-width: 50%;
float: right;
}
.FAQcontainer{ /* you can not have space in class names */
clear: both;
}
This way the Image-Div will be shown on the right side. If it does not contain an image, then it will be very small. If it conatins an image, it will not be wider than 50% of the FAQcontainer-Div.
Please be aware that some older browsers do not understand 'max-width'. And if the image is wider than this 50%, it will take it place and "destroy" the layout.
A more reliable solution would be to generate these DIVs dynamically by a server-side Script which prints out the Image-Div only if needed. The script could also take care of the different images sizes.
There are many ways of doing this - with PHP or JavaScript:
PHP
You could apply different classes depending on whether their is a image or not, and then style them differently. If each answer/image set is stored as an array, you can check to see if an image is applied then echo a class if the image is not empty.
JavaScript
This would be the method I would be inclined to use. With JavaScript, check to see if an image is their, then change the styles appropriately. However, make sure there is an appropriate CSS only fallback for browsers with JS disabled (e.g. have image above text for those users).