I am wondering if it's possible to create a grid-like layout using div's that are dynamically created using PHP.
I am creating a product page that will display all products in a PHP database. I want each product to be housed in a div, and 3 divs to display in a row with as many rows as needed to get through all the products.
Something like this:
div div div
$row['product1'] $row['product2'] $row['product3']
div div div
$row['product4'] $row['product5'] $row['product6']
I would prefer not to use a table. I know how to line divs up using the float and clear properties, but not if they are all being created in a while statement, which makes me think it might not be possible.
So I guess, is this possible without using tables, or should I just stick with that?
This can be done the way you ask, though it isn't the best way. It's entirely possible to identify the <div> positions within columns in a while loop:
// Looping over your results simplified...
$i = 1;
while ($results) {
if ($i % 3 == 1) {
$div_class = 'left';
}
else if ($i % 3 == 2) {
$div_class = 'middle';
}
else {
$div_class = 'right';
}
$i++;
// output, simplified
echo "<div class='$div_class'>$row_contents</div>";
}
Then use your CSS to float and clear as necessary for the left, middle, right classes.
.left, .middle, .right {
float: left;
}
.left { clear: left; }
.right { clear: right; }
However,
Given all of this, I still probably wouldn't bother with <div>s. Semantically if this is a list of products, you should be listing them in <li> tags. Then just style the <li> to float: left; and make each one 33% the width of the container so you get 3 per line.
Related
What I'm looking for is a way to print two complete form elements next to each other as they go down a php page. Essentially two columns of repeating elements.
I have a "div" loop that creates multiple elements on my page using the same div I guess? I'm using two variables to set their location on the page as it goes down, ex. ($down += 200, $left += 200) and it works pretty well. The problem I'm facing is that I have to put an excessive amount of space between each element because some parts are 20px tall and some are 50px tall. With the div loop it looks like they're not aware of each other as far as I can tell meaning all the smaller ones cause the next larger element not to move far enough down the page making them overlap. It'd rather not account for each individual one to only have it do extra space on the smaller ones. I feel like there should be a better option for this. I would also like to avoid a table unless someone can show me a table without the table portion and just the formatting.
while ($results = mysqli_fetch_assoc($towerquery))
{
if ($number % 2 == 0 && $number !== 0 ){ $left = 200; $down += 320; }
print '<span style="display:block;position:relative;left:'.$left.'px;top:'.$down.'px;font-family:tahoma;font-size:13px;margin:40px;">';
$down -= 300;
$left += 500;
}
You can always use Flexbox to create equal height divs:
.paddingBlock {
padding: 20px 0;
}
.eqDisplay {
display: flex;
}
.equal {
padding: 10px;
}
.equal:nth-of-type(odd) {
background: darkgreen;
}
.equal:nth-of-type(even) {
background: black;
}
.eqHW {
flex: 1;
}
.eqHWrap {
justify-content: space-between;
color: #eee;
}
<div class="paddingBlock">
<h1>Equal Column Height</h1>
<div class="eqHWrap eqDisplay">
<div class="eqHW equal">
<p>Using</p>
<p>flex</p>
</div>
<div class="eqHW equal">
<p>works</p>
<p>well</p>
<p>despite</p>
<p>content</p>
<p>length</p>
</div>
</div>
</div>
Using that in php you could echo the results:
<?php
$yourVariable = array(1,9,5,12,73);
echo '<div class="paddingBlock"><div class="eqHWrap eqDisplay">';
while (x === x) {
echo '<div class="eqHW equal">' . $yourVariable . '</div>';
}
echo '</div></div>';
?>
The answer above definitely what lead me down the path to victory and dominance of my webpage, but I had to add a separate part to make it work for me which I have posted below
$number = 0;
if ($number % 2 == 0 || $number == 0 ) { print '<div class="eqHWrap eqDisplay">'; }
print '<div class="eqHW equal">';
print '<p>';
//multiple if statements, span elements, line breaks, returns
print '</p>';
if ($number % 2 !== 0 && $number !== 0 ) { print '</div>'; }
print '</div>';
$number++;
This extra code allowed me to only use one div and have it execute as two, because I'm pulling from an array of IPs and I can't get current and get next at the same time due to the coding disasters I kept running into. I assume other people run into the same problem when creating a loop to pull from an array as you can typically only do one at a time in sequence. My code is now successfully working though as seen below in the link!
I have a file that holds an array of navigation links, so that if I want to add a new link to the nav menu I can do it in one file rather than have to change multiple manually. However, each menu link (category) requires a different a:hover colour, but my current coding doesn't work.
Here's the file where the menu items are stored, along with the colour that should be the a:hover colour in a multi-indexed array (some are left blank):
<?php
$CATEGORIES = array(
array("culture", "#f9993c"),
array("nature", "#59AF56"),
array("science", "COLOUR"),
array("society", "COLOUR"),
array("technology", "COLOUR")
);
?>
Here's the file that prints the menu items:
<?php
$count_categories = count($CATEGORIES);
$incr_categories = 0;
while($incr_categories != $count_categories) {
// Change main_right_sub a:hover
echo "<style>#main_right_sub a:hover { color: ".$CATEGORIES[$incr_categories][1]."; } </style>";
// Print Nav Items
echo "<a href='category.php?cat?=".$CATEGORIES[$incr_categories][0]."'>".strtoupper($CATEGORIES[$incr_categories][0])."</a>";
// Increment Count
$incr_categories++;
if ($incr_categories != $count_categories) {
echo " | ";
}
}
?>
I'm guessing you can't interchange a style like that, because all the links are coming out as "#59AF56" on mouseover, which is odd as that is the second colour in the multi-index array. Any help would be appreciated!
You can set the categories as CSS classes on your links so that the resulting link looks like this, for example:
CULTURE
And then define CSS styles for each link class with the necessary colors (either by generating them in your PHP code or by defining them in a static CSS file. For example, for the culture link as in the above example:
#main_right_sub a.culture:hover
{
color: #f9993c;
}
First of all css doesn't load after each element as you might think, the browser will use whatever rule that has the highest priority on all of your elements, what you could do is make use of inline css styling, but unfortunately :hover isn't supporter so your last resort is basically javascript
<a
href="link.php"
onMouseOver="this.style.color='#FFF'"
onMouseOut="this.style.color='#000'"
>Text</a>
but the optimal way would be without any doubt be the use of classes, give every colortheme a class and add those classes to desired elements as needed.
I am creating multiple divs in a loop in php shown below.
<?php
for ($i=0; $i<=9; $i++)
{
for ($j=0; $j<=9; $j++)
{
echo "<div class=\"bg\" id=\"aaa".$i."\" style=\" position:absolute;top:".($i*10)."%;left:".($j*10)."%;\">
</div>";
}
}
?>
i want to select multiple divs (not all) and change their backgrounds using jquery. i cant seem to be able to figure out how to proceed with this
You can select div with id starting with aaa
$('div[id^=aaa]')
if you want to select yhe div's based on their index, you could use the nth-of-type selector:
divs = $('.bg:nth-of-type(1)');
divs.css('background-color','blue');
You can select multiple elements by adding them to the variable:
divs.add('.bg:nth-of-type(2)').add('.bg:nth-of-type(3)');
Note that these are css selectors so it may be an idea to simply do this in css:
.bg:nth-of-type(1),
.bg:nth-of-type(2),
.bg:nth-of-type(3){
background-color: blue;
}
also note you can use an expression inside the brackets to represent multiple values in a sequence.
.bg:nth-of-type(3n+1){ //will select every fourth div
background-color: blue;
}
Unless you can come up with a better criteria for which div's you want to change, this is probably the best way.
Source(s)
jQuery API - .add()
MDN - CSS :nth-of-type selector
This should do the trick:
var arrayDivs = $('div[id^=aaa]');
$.each(arrayDivs, function(){
$(this).css('background-color', '#000');
});
If you want to select multiple lists and not all "aaa"+integer ones, you will need to either know the numbers of those or you need to differ within your loops already.
More information would be awesome!
The "proper" way (if you can say that) would be to group the elements you want to assign common properties with appropriate classes. You can then manipulate them via CSS
So in essense, while looping in the above code :
for ($i=0; $i<=9; $i++) {
for ($j=0; $j<=9; $j++) {
$classes = 'bg';
if( [somelogic] ) { $classes .= ' bluefront'; }
if( [otherlogic] ) { $classes .= ' greenback'; }
echo "<div class=\"".$classes."\" id=\"aaa".$i."\" style=\" position:absolute;top:".($i*10)."%;left:".($j*10)."%;\"></div>";
}
}
and then, via CSS :
.bg.bluefront { color: blue; }
.bg.greenback.bluefront { background-color: green; color: white; }
//select all elements with class bg and add background image
$('.bg').css('background-image',"url('some_image.gif')");
better yet use css:
.bg {
background-image: url('some_image.gif');
}
if you only want some divs from the class bg:
$('.bg').each(function(index,element){
//your code here eg:
if(index == 2)
alert(index);
});
Basically I am createing a unknown size of checkboxs that is dependent on the row that is chosen from a table in my database. The reason I dont know the size is that the user chooses which row they will use with some rows containing what will become 10 checkboxs adn others containing as many as 75. So the problem is that if the user selects a row with a large amount of options it goes through the border of my div and then forces me to scroll the page down what I am looking for is a way to say >
if(number of checkboxs is >25 )
create a new column on my page
I dont know whether the right way to go about this is to use php or javascript or possibly do it using css I am new to all of these languages so any help no matter how trivial will greatly appreciated.
<div id="major1">
<?php
$courses=mysql_query("SELECT * FROM MAJORS_CHECKLIST WHERE MAJOR='$major'");
$courses_row=mysql_fetch_row($courses);
$count = 0;
echo "$courses_row[0] <br/>";
$checkit = 0;
$sidebyside = 0;
foreach($courses_row as $i=>$courses_row){
if($courses_row['$count'] == NULL)
{
break;//if we run out of courses stop printing them
}
if($courses_row[$count] == $courses_row[0] && $checkit == 0 )
{
$checkit = $checkit + 1;
}
else
{
echo "<input type='checkbox' value='$courses_row' name='majorCourses[]' /> ";//answer-$i
echo "$courses_row<br /> ";
}
$count = $count + 1;
/*$sidebyside++;
if($sidebyside == 2)//tried using this to put 2 checkboxes side by side that ened up just messing everything up
{
echo "<br/>";
$sidebyside = 0;
}*/
}
?>
here is my css:
#major1{
color: white;
/*border: 1px solid black;*/
padding: 5px;
float: left;
height:500px;
width:150px;
}
Producing a bunch of checkboxes in the div can be controlled using CSS. Should set the parent div of the checkboxes to the following rules: width:auto; height:auto; padding:10px 10px; position:relative; This is all assuming that the parent div of the checkboxes is a child of another div to control the preferred dimensions
edit: if you do not want to want to use css with the methods above, you can control the "X" amount of checkboxes per row. You can create a counter to count how many are being displayed and do a if($counter % X == 0) echo "</div><div>"; This is all assuming you have a starting div at the beginning of your code and an ending div at the end of the code.
I am trying to display a recursive list in PHP for a site I am working on.
I am really having trouble trying to get the second level to display. I have a function that displays the contents to the page as follows.
function get_menu_entries($content,$which=0)
{
global $tbl_prefix, $sys_explorer_vars, $sys_config_vars;
// INIT LIBRARIES
$db = new DB_Tpl();
$curr_time = time();
$db->query("SELECT * FROM ".$tbl_prefix."sys_explorer WHERE preid = '".$which."' && config_id = '".$sys_explorer_vars['config_id']."' && blocked = '0' && startdate < '".$curr_time."' && (enddate > '".$curr_time."' || enddate = '') ORDER BY preid,sorting");
while($db->next_record()){
$indent = $db->f("level") * 10 - 10;
$sitemap_vars['break'] = "";
$sitemap_vars['bold'] = "";
if($db->f("level") == 2) {
$sitemap_vars['ul_start'] = "";
$sitemap_vars['bold'] = "class='bold'";
$sitemap_vars['ul_end'] = "";
}
switch($db->f("link_type"))
{
case '1': // External Url
$sitemap_vars['hyperlink'] = $db->f("link_url");
$sitemap_vars['target'] = "";
if($db->f("link_target") != "") {
$sitemap_vars['target'] = "target=\"".$db->f("link_target")."\"";
}
break;
case '2': // Shortcut
$sitemap_vars['hyperlink'] = create_url($db->f("link_eid"),$db->f("name"),$sys_config_vars['mod_rewrite']);
$sitemap_vars['target'] = "";
break;
default:
$sitemap_vars['hyperlink'] = create_url($db->f("eid"),$db->f("name"),$sys_config_vars['mod_rewrite']);
$sitemap_vars['target'] = "";
break;
}
if($db->f("level") > 1) {
$content .= "<div style=\"text-indent: ".$indent."px;\" ".$sitemap_vars['bold'].">".$db->f("name")."</div>\n";
}
$content = get_menu_entries($content,$db->f("eid"));
}
return(''.$content.'');
}
At the moment the content displays properly, however I want to turn this function into a DHTML dropdown menu.
At present what happens with the level 2 elements is that using CSS the contents are indented using CSS. What I need to happen is to place the UL tag at the beginning and /UL tag at the end of the level 2 elements.
I hope this makes sense. Any help would be greatly appreciated.
Instead of using <div> tags with indentation, use an unordered list for each level, including the first one. Have your function output <ul> at the start and </ul> at the end, and change <div style="text-indent: ..."> to a simple <li>. Give the first level an ID so you can hook onto it. Then you can use CSS to remove bullet points and change the indentation, etc. You don't need to calculate the indentation or whether to bold the text in PHP—instead, use selectors and allow the browser to figure it out:
ul#menu { margin: 0; padding: 0; }
ul#menu > li { margin: 0; padding: 0; }
ul#menu > li > ul { margin-left: 10px; font-weight: bold; }
All this will allow you to use one standard algorithm for generating your list, instead of branching based on the level, as well as making the menu look like a menu to web crawlers, search engines and those with CSS-less browsers.
By the way, you should really be htmlspecialchars-ing all that dynamic text. You don't want a stray < to mess up your markup.
Correct me if I'm wrong, but it seems that your issue is not that you don't know when to print the first set of <ul> tags, but that you are trying to print the second set (for level 2) in every function call, and thus ending up with too many open/close tags.
I think what you should try to do is sort your array by level, first (see uasort() and then you can output your opening <ul> tag on the first loop of the second level (use a counter to keep track of which loop you're on and then do something like if ($i == 0) or if ($i == (count($array) - 1)). This will work no matter how many nested levels you have.