728x90


I'm using jQuery in my site and I would like to trigger certain actions when a certain div is made visible.

Is it possible to attach some sort of "isvisible" event handler to arbitrary divs and have certain code run when they the div is made visible?

I would like something like the following pseudocode:

$(function() {
  $('#contentDiv').isvisible(function() {
    alert("do something");
  });
});

The alert("do something") code should not fire until the contentDiv is actually made visible.

Thanks.

shareimprove this question
up vote167down voteaccepted

You could always add to the original .show() method so you don't have to trigger events every time you show something or if you need it to work with legacy code:

Jquery extension:

jQuery(function($) {

  var _oldShow = $.fn.show;

  $.fn.show = function(speed, oldCallback) {
    return $(this).each(function() {
      var obj         = $(this),
          newCallback = function() {
            if ($.isFunction(oldCallback)) {
              oldCallback.apply(obj);
            }
            obj.trigger('afterShow');
          };

      // you can trigger a before show if you want
      obj.trigger('beforeShow');

      // now use the old function to show the element passing the new callback
      _oldShow.apply(obj, [speed, newCallback]);
    });
  }
});

Usage example:

jQuery(function($) {
  $('#test')
    .bind('beforeShow', function() {
      alert('beforeShow');
    }) 
    .bind('afterShow', function() {
      alert('afterShow');
    })
    .show(1000, function() {
      alert('in show callback');
    })
    .show();
});

This effectively lets you do something beforeShow and afterShow while still executing the normal behavior of the original .show() method.

You could also create another method so you don't have to override the original .show() method.

shareimprove this answer
5 
EDIT: There is only one downside with this method: You will have to repeat the same "extension" for all methods that reveal the element: show(), slideDown() etc. Something more universal is required to solve this problem for once and all, since its impossible to have "ready" event for delegate() or live(). – Shahriyar Imanov Feb 24 '11 at 17:59
   
Good, the only problem is that fadeTo function does not work properly after implementing this function – Omid Nov 11 '11 at 10:56
8 
Your code does not appear to work with the latest jQuery (1.7.1 at the date of this comment). I have reworked this solution slightly to work with the latest jQuery: stackoverflow.com/a/9422207/135968 – mkmurray Feb 23 '12 at 22:15
2 
Thanks mkmurray. It at least worked for a few years! – Tres Aug 15 '13 at 1:37
   
Can't get that code to work with div visibility triggered by an ajax response. – JackTheKnife Oct 7 '16 at 14:39


728x90

Description ¶

array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

Parameters ¶

delimiter

The boundary string.

string

The input string.

limit

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

If the limit parameter is negative, all components except the last -limit are returned.

If the limit parameter is zero, then this is treated as 1.

Note:

Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that thedelimiter argument comes before the string argument.

Return Values ¶

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

Changelog ¶

VersionDescription
5.1.0Support for negative limits was added

Examples ¶

Example #1 explode() examples

<?php
// Example 1
$pizza  "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces explode(" "$pizza);
echo 
$pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data "foo:*:1023:1000::/home/foo:/bin/sh";
list(
$user$pass$uid$gid$gecos$home$shell) = explode(":"$data);
echo 
$user// foo
echo $pass// *

?>

Example #2 explode() return examples

<?php
/* 
   A string that doesn't contain the delimiter will simply
   return a one-length array of the original string.
*/
$input1 "hello";
$input2 "hello,there";
$input3 ',';
var_dumpexplode','$input1 ) );
var_dumpexplode','$input2 ) );
var_dumpexplode','$input3 ) );

?>

The above example will output:

array(1)
(
    [0] => string(5) "hello"
)
array(2)
(
    [0] => string(5) "hello"
    [1] => string(5) "there"
)
array(2)
(
    [0] => string(0) ""
    [1] => string(0) ""
)

Example #3 limit parameter examples

<?php
$str 
'one|two|three|four';

// positive limit
print_r(explode('|'$str2));

// negative limit (since PHP 5.1)
print_r(explode('|'$str, -1));
?>

The above example will output:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

Notes ¶

NoteThis function is binary-safe.

See Also ¶

add a note add a note

User Contributed Notes 26 notes

php at metehanarslan dot com ¶
4 years ago
Here is my approach to have exploded output with multiple delimiter. 

<?php

//$delimiters has to be array
//$string has to be array

function multiexplode ($delimiters,$string) {
    
    
$ready str_replace($delimiters$delimiters[0], $string);
    
$launch explode($delimiters[0], $ready);
    return  
$launch;
}

$text "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded multiexplode(array(",",".","|",":"),$text);

print_r($exploded);

//And output will be like this:
// Array
// (
//    [0] => here is a sample
//    [1] =>  this text
//    [2] =>  and this will be exploded
//    [3] =>  this also 
//    [4] =>  this one too 
//    [5] => )
// )

?>
tiago dot dias at flow-me dot com ¶
7 years ago
Beaware splitting empty strings.

<?php
$str 
"";
$res explode(","$str);
print_r($res);
?>

If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value.

Array
(
    [0] => 
)

To solve this, just use array_filter() without callback. Quoting manual page "If the callback function is not supplied, array_filter() will remove all the entries of input that are equal to FALSE.".

<?php
$str 
"";
$res array_filter(explode(","$str));
print_r($res);
?>

Array
(
)
Hayley Watson ¶
4 years ago
The comments to use array_filter() without a callback to remove empty strings from explode's results miss the fact that array_filter will remove all elements that, to quote the manual,  "are equal to FALSE".

This includes, in particular, the string "0", which is NOT an empty string.

If you really want to filter out empty strings, use the defining feature of the empty string that it is the only string that has a length of 0. So:
<?php
array_filter
(explode(':'"1:2::3:0:4"), 'strlen');
?>
kenorb at niepodam dot pl ¶
2 years ago
If you need to split by multiple characters, use preg_split() instead:

    $new_string = preg_split("/[&=:]/", $string);
eye_syah88 at yahoo dot com ¶
6 years ago
a simple one line method to explode & trim whitespaces from the exploded elements

array_map('trim',explode(",",$str));

example:

$str="one  ,two  ,       three  ,  four    "; 
print_r(array_map('trim',explode(",",$str)));

Output:

Array ( [0] => one [1] => two [2] => three [3] => four )
m0gr14 at gmail dot com ¶
7 years ago
Here's a function for "multi" exploding a string.

<?php
//the function
//Param 1 has to be an Array
//Param 2 has to be a String
function multiexplode ($delimiters,$string) {
    
$ary explode($delimiters[0],$string);
    
array_shift($delimiters);
    if(
$delimiters != NULL) {
        foreach(
$ary as $key => $val) {
             
$ary[$key] = multiexplode($delimiters$val);
        }
    }
    return  
$ary;
}

// Example of use
$string "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
$delimiters = Array(",",":","|","-");

$res multiexplode($delimiters,$string);
echo 
'<pre>';
print_r($res);
echo 
'</pre>';

//returns
/*
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                        )

                    [1] => Array
                        (
                            [0] => 4
                            [1] => 5
                        )

                    [2] => Array
                        (
                            [0] => 6
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 7
                            [1] => 8
                            [2] => 9
                            [3] => 0
                        )

                    [1] => Array
                        (
                            [0] => 1
                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 2
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 3
                            [1] => 4
                        )

                    [1] => Array
                        (
                            [0] => 5
                        )

                )

        )

)
*/
?>
Anonymous ¶
8 years ago
<?php
// converts pure string into a trimmed keyed array
function string2KeyedArray($string$delimiter ','$kv '=>') {
  if (
$a explode($delimiter$string)) { // create parts
    
foreach ($a as $s) { // each part
      
if ($s) {
        if (
$pos strpos($s$kv)) { // key/value delimiter
          
$ka[trim(substr($s0$pos))] = trim(substr($s$pos strlen($kv)));
        } else { 
// key delimiter not found
          
$ka[] = trim($s);
        }
      }
    }
    return 
$ka;
  }
// string2KeyedArray

$string 'a=>1, b=>23   , $a, c=> 45% , true,d => ab c ';
print_r(string2KeyedArray($string));
?>

Array
(
  [a] => 1
  [b] => 23
  [0] => $a
  [c] => 45%
  [1] => true
  [d] => ab c
)
kkobashi at kobashicomputing dot com ¶
5 years ago
Explode does not parse a string by delimiters, in the sense that we expect to find tokens between a starting and ending delimiter, but instead splits a string into parts by using a string as the boundary of each part. Once that boundary is discovered the string is split. Whether or not that boundary is proceeded or superseded by any data is irrelevant since the parts are determined at the point a boundary is discovered. 

For example: 

<?php 

var_dump
(explode("/","/")); 

/* 
   Outputs 

   array(2) { 
     [0]=> 
     string(0) "" 
     [1]=> 
     string(0) "" 
   } 
*/ 

?> 

The reason we have two empty strings here is that a boundary is discovered before any data has been collected from the string. The boundary splits the string into two parts even though those parts are empty. 

One way to avoid getting back empty parts (if you don't care for those empty parts) is to use array_filter on the result. 

<?php 

var_dump
(array_filter(explode("/","/"))); 

/* 
   Outputs 

   array(0) { 
   } 
*/ 
?> 

*[This note was edited by googleguy at php dot net for clarity]*
wado ¶
3 years ago
It should be said that when an empty delimiter is passed to explode, the function not only will return false but will also emit a warning.

<?php
var_dump
explode('','asdasd') );

/**
  * Output:
  * Warning: explode(): Empty delimiter in ...
  * bool(false)
  */
?>
auramgold ¶
7 months ago
Simple function to explode a string with keys specified in the string.

<?php
function explode_with_keys($delim1,$delim2,$inputstring)
{
    
$firstarr explode($delim1,$inputstring);
    
$finalarr = array();
    foreach(
$firstarr as $set)
    {
        
$setarr explode($delim2,$set);
        
$finalarr[$setarr[0]] = $setarr[1];
    }
    return 
$finalarr;
}

print_r(explode_with_keys(";",":","a:b;c:d;e:f"));
?>

Will output:
Array ( [a] => b [c] => d [e] => f )
Manngo ¶
1 year ago
Sometimes I want to create a MINIMUM length array. For example, if the delimiter is not present at all, you might still want an empty additional item.

This can be done by adding the delimiter to the string as follows:

<?php
    $data
='a';
    
$array=explode(':',"$data:");
    
print_r($array);
?>

If you want an EXACT number of elements, you can combine this with array_slice:

<?php
    $data
='a:::';
    
$array=explode(':',"$data:");
    
$array=array_slice($array,0,2);    //    exactly 2 elements
    
print_r($array);
?>
artaxerxes2 at iname dot com ¶
3 years ago
Note that using explode() on an empty string returns a non-empty array.

So the code:
<?php
  print_r
(explode("|","");
?>
returns:
Array
(
    [0] => 
)

If you need to return an empty array in the case of an empty string, you must call array_diff() after the explode:
<?php
  print_r
(array_diff(explode("|",""),array("")));
?>
returns:
Array
(
)

This is useful in case your use of MySQL's group_concat() returns an empty string for just some records but you want to convert them all to arrays that actually reflect what group_concat() gave you
Cody G. ¶
7 years ago
I'm sure you guys get just a bit frustrated at times when you need a fraction of a very simple string and you use "explode()", but then you have to define a whole extra variable. (That is because you need to store a function-returned array in a variable before you can extract a value).

If you're extracting the last half, or third, of a string, there's an easy inline workaround. Check this:

<?php
$mystr 
"separated-text";
print(
str_replace("-","",strstr("-",$mystr)));
//Returns "text"
?>

If the separator (dash) can be left in, you don't even need the "str_replace()" function.

Lets try this with 3 fractions:

<?php
$mystr 
"separated-text-again";
//Comment submission wouldn't let me
// combine this into one statement.
// That's okay, it's more readable.
$split1 str_replace("-","",strstr("-",$mystr));
print(
str_replace("-","",strstr("-",$split1)));
//Returns "again"
?>

Anything more than 3 fractions gets really confusing, in that case you should use "explode()".

Hope this helps!
~Cody G.
coroa at cosmo-genics dot com ¶
14 years ago
To split a string containing multiple seperators between elements rather use preg_split than explode:

preg_split ("/\s+/", "Here  are    to    many  spaces in   between");

which gives you
array ("Here", "are", "to", "many", "spaces", "in", "between");
nick dot brown at free dot fr ¶
8 years ago
My application was running out of memory (my hosting company limits PHP to 32MB).  I have a string containing between 100 and 20000 triplets, separated by a space, with each triplet consisting of three double-precision numbers, separated by commas.  Total size of the biggest string, with 20000 triplets, is about 1MB.

The application needs to split the string into triplets, then split the triplet into numbers.  In C, this would take up about 480K (20000 times 3 x 8 bytes) for the final array.  The intermediate array of strings shouldn't be much bigger than the long string itself (1MB).  And I expect some overhead from PHP, say 300% to allow for indexes etc.

Well, PHP5 manages to run out of memory *at the first stage* (exploding the string on the space character).  I'm expecting to get an array of 20000 strings, but it needs more than 32MB to store it.  Amazing.

The workaround was easy and had the bonus of producing faster code (I compared it on a 10000 triplet string).  Since in any case I had to split up the numeric triplets afterwards, I decided to use preg_match_all() on the original string.  Despite the fact that the resulting "matches" array contains more data per element than the result of explode() - because it stores the matched triplet, plus its component numbers - it takes up far less memory.

Moral: be careful when using explode() on big strings, as it can also explode your memory usage.
david dot drakulovski at gmail dot com ¶
3 years ago
I made this code for some useful filtering texts with lot of gibberish. Example provided:

<?php
$text 
"There are;many|variations of:passages of Lorem Ipsum available,but the/majority have\"suffered|alteration in some form,by injected humour,or randomised words which don't look even.slightly:believable./";

$delimiter = array(" ",",",".","'","\"","|","\\","/",";",":");
$replace str_replace($delimiter$delimiter[0], $text);
$explode explode($delimiter[0], $replace);

echo 
'<pre>';
print_r($explode);
echo 
'</pre>';
// replaces many symbols in text, then explodes it
?>

This will output the following:
Array
(
    [0] => There
    [1] => are
    [2] => many
    [3] => variations
    [4] => of
    [5] => passages
    [6] => of
    [7] => Lorem
    [8] => Ipsum
    [9] => available
    [10] => but
    [11] => the
    [12] => majority
    [13] => have
    [14] => suffered
    [15] => alteration
    [16] => in
    [17] => some
    [18] => form
    [19] => by
    [20] => injected
    [21] => humour
    [22] => or
    [23] => randomised
    [24] => words
    [25] => which
    [26] => don
    [27] => t
    [28] => look
    [29] => even
    [30] => slightly
    [31] => believable
    [32] => 
    [33] => 
)
dhz ¶
7 years ago
A one-liner to extract a portion of a string, starting from the END of the string....
<?php
$extracted_string 
implode('.'array_slice(explode('.'$original_string), -2));
?>
m.reesinck ¶
4 years ago
I needed a multiexplode which didn't replace my delimiters for 1 other delimiter. Because I couldn't find one in the examples I made one. 

delimiter array: 
array('/RTRN/','/BUSP/','/BENM/','/ORDP/','/CSID/', '/MARF/','/EREF/', '/PREF/','/REMI/','/ID/','/PURP/', '/ULTB/','/ULTD/'); 

input string: /RTRN/MS03//BENM/NL50INGB00012345/BUSP/Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB///CSID/NL32ZZZ999999991234//MARF/EV45451//EREF/EV45451 REP170112T1106//REMI///EV45451REP170112T1106/ 

output: 
array( 
[/RTRN/] => MS03/ 
[/BENM/] => NL50INGB00012345 
[/BUSP/] => Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB// 
[/CSID/] => NL32ZZZ999999991234/ 
[/MARF/] => EV45451/ 
[/EREF/] => EV45451REP170112T1106/ 
[/REMI/] => //EV45451REP170112T1106/ 
[/ORDP/] => 
[/PREF/] => 
[/ID/] => 
[/PURP/] => 
[/ULTB/] => 
[/ULTD/] => 


<?php 
function multiexplode($delimiters,$string) { 
            
        
$arrOccurence = array(); 
        
$arrEnd = array(); 
        foreach(
$delimiters as $key => $value){ 
            
$position strpos($string$value); 
            if(
$position > -1){ 
                
$arrOccurence[$value] = $position
            } 
        } 
        
        if(
count($arrOccurence) > 0){ 
                
            
asort($arrOccurence); 
            
$arrEnd array_values($arrOccurence); 
            
array_shift($arrEnd); 
    
            
$i 0
            foreach(
$arrOccurence as $key => $start){ 
                
$pointer $start+strlen($key); 
                if(
$i == count($arrEnd)){ 
                    
$arrOccurence[$key] = substr($string$pointer); 
                } else { 
                    
$arrOccurence[$key] = substr($string$pointer$arrEnd[$i]-$pointer); 
                } 
                
$i++; 
            } 
            
        } 

         
//next part can be left apart if not necessary. In that case key that don't appear in the inputstringwill not be returned 
        
foreach($delimiters as $key => $value){ 
            if(!isset(
$arrOccurence[$value])){ 
                
$arrOccurence[$value] = ''
            } 
        } 

        return 
$arrOccurence

?>
dark dot side01 at yahoo dot com ¶
1 year ago
(excuse my english)
When I try to use explode to know if a string contains many words, I noticed this :

<?php
      $sentence
"  word ";
      
$array explode($sentence); 
       
var_dump($array);
?>
return this :

array(4) {
  [0]=>  string(0) ""
  [1]=>  string(0) ""
  [2]=>  string(4) "word"
  [3]=>  string(0) ""
}

So, "explode" didn't keep the delimiter but counts it. You have to use trim($sentence) to count words in a sentence.  ^v^
seventoes at gmail dot com ¶
11 years ago
Note that explode, split, and functions like it, can accept more than a single character for the delimiter.

<?php
$string 
"Something--next--something else--next--one more";

print_r(explode('--next--',$string));
?>
SR ¶
8 years ago
Keep in mind that explode() can return empty elements if the delimiter is immediately repeated twice (or more), as shown by the following example:

<?php
$foo 
'uno dos  tres'// two spaces between "dos" and "tres"
print_r(explode(' '$foo));
?>

Array
(
    [0] => uno
    [1] => dos
    [2] => 
    [3] => tres
)

Needless to say this is definitely not intuitive and must be handled carefully.
crog at gustavus dot edu ¶
4 years ago
Note that while the documentation states the "If limit is set and positive," passing a null-value will still result in triggering the "limit is zero" case (as of PHP 5.4.17).

When passing through values (such as using explode to implement an interface method), you'll need to explicitly check that the limit has been set:

<?php
  
public function split($string$delimiter$limit null)
  {
    return isset(
$limit) ? explode($delimiter$string$limit) : explode($delimiter$string);
  }
?>

Failing to check $limit and simply passing through a null-value will return the same value as if $limit were 0 or 1. To clarify, all of the following will return the same value:

<?php
explode
($string$delimiternull);
explode($string$delimiter0);
explode($string$delimiter1);
?>
KEINOS ¶
2 days ago
If you want to have delimiter option as an array WITH limit option.
( an extended approach from php-at-metehanarslan-dot-com's )

<?php
/**
* explode_multi function.
*
* Split a string by an array of string and limitable
*
* @access public
* @param  array    $delimiters
* @param  string   $string_raw
* @param  integer  $limit (default: PHP_INT_MAX)
* @return array
*/
function explode_multi($delimiters$string_raw$limit PHP_INT_MAX)
{
    
$string_tmp = (string) $string_raw;
    
$string_rep str_replace($delimiters$delimiters[0], $string_raw);
    
$exploded   explode($delimiters[0], $string_rep$limit);
    
$result     = array();
    for (
$key 0$key < ($limit-1); $key++) {
        
$pattern    $exploded[$key];
        
$string_tmp preg_replace("/${pattern}/"''$string_tmp1);
        
$result[]   = $pattern;
    }
    
$result[] = trim($string_tmp);

    return 
$result;
}

?>
MarkAgius at markagius dot co dot uk ¶
8 months ago
As you can not send an enclosure value to explode, use str_getcsv,
if you want to explode a string when the delimiter is in some cells. (Comma in quotes)

<?php
  $a 
"aaa1,bbb1,'ccc,ccc1',ddd1";
  
$b 'aaa2,bbb2,"ccc,ccc2",ddd2';

  
// This dosn't work as it splits 'ccc,ccc1' and "ccc,ccc2".

  
print "<PRE>a output using explode():\n";
  
print_rexplode(",",$a) );
  print 
"</PRE>\n";

  print 
"<PRE>b output using explode():\n";
  
print_rexplode(",",$b) );
  print 
"</PRE>\n";

  
// This works.

  
print "<PRE>a output using str_getcsv():\n";
  
print_rstr_getcsv($a,",","'") );
  print 
"</PRE>\n";

  print 
"<PRE>b output using str_getcsv():\n";
  
print_rstr_getcsv($b,",","\"") );
  print 
"</PRE>\n";

?>
explode() returns;
    [0] => aaa1
    [1] => bbb1
    [2] => 'ccc
    [3] => ccc1'
    [4] => ddd1

str_getcsv() returns;
    [0] => aaa1
    [1] => bbb1
    [2] => ccc,ccc1
    [3] => ddd1
Anonymous ¶
8 years ago
Note to the previous example: we can do the whole string->array conversion using explode() exclusively. 

<?php
    
// converts pure string into a trimmed keyed array
    
function string_2_array$string$delimiter ','$kv '=>')
    {
        if (
$element explode$delimiter$string ))
        {
            
// create parts
            
foreach ( $element as $key_value )
            {
                
// key -> value pair or single value
                
$atom explode$kv$key_value );

                if( 
trim($atom[1]) )
                {
                  
$key_arr[trim($atom[0])] = trim($atom[1]);
                }
                else
                {
                    
$key_arr[] = trim($atom[0]);
                }
            }
        }
        else
        {
            
$key_arr false;
        }

        return 
$key_arr;
    }
?>
locoluis at gmail dot com ¶
7 years ago
That with all stateful encodings that use bytes between 0x00 and 0x7f for something other than, say, encoding ASCII characters. Including GBK, BIG5, Shift-JIS etc.

explode and other such PHP functions work on bytes, not characters.

What you do is to convert the string to UTF-8 using iconv(), then explode, then go back to GBK.


'WEB' 카테고리의 다른 글

[PHP] swtich  (0) 2018.01.23
How to use PHP string in mySQL LIKE query?  (0) 2018.01.22
[PHP] mysqli::num_rows  (0) 2018.01.14
[PHP] filter_var function vs number_format  (0) 2018.01.14
mysqli::real_escape_string  (0) 2018.01.14
728x90

문단의 들여쓰기를 조절하는 속성입니다. 속성 값은 px나 em 등의 수치로 넣을 수 있으며, 값이 양수(+)일 경우 들여쓰기가 되고, 음수(-)일 경우 내어 쓰기가 됩니다.

이 text-indent를 이용해서 글자를 감추고 이미지로 대체하기도 합니다. 이러한 사용은 나중에 따로 살펴보겠습니다.

적용 예시

이 문단은 text-indent에 양수 값을 적용하여 문단 시작에 들여쓰기를 적용했습니다. 이렇게 들여쓰기를 함으로써, 새로운 문단의 시작을 표현할 수 있습니다. 이 문단은 text-indent에 양수 값을 적용하여 문단 시작에 들여쓰기를 적용했습니다. 이렇게 들여쓰기를 함으로써, 새로운 문단의 시작을 표현할 수 있습니다. 이 문단은 text-indent에 양수 값을 적용하여 문단 시작에 들여쓰기를 적용했습니다. 이렇게 들여쓰기를 함으로써, 새로운 문단의 시작을 표현할 수 있습니다.

이 문단은 text-indent에 음수 값을 적용하여 내어 쓰기를 적용했습니다. 안에 여백을 주지 않고 음수 값을 주게 되면 영역을 벗어날 수 있으니, 여백을 같이 주는 것이 좋습니다. 이 문단은 text-indent에 음수 값을 적용하여 내어 쓰기를 적용했습니다. 안에 여백을 주지 않고 음수 값을 주게 되면 영역을 벗어날 수 있으니, 여백을 같이 주는 것이 좋습니다. 이 문단은 text-indent에 음수값을 적용하여 내어쓰기를 적용했습니다. 안에 여백을 주지않고 음수값을 주게 되면 영역을 벗어날 수 있으니, 여백을 같이 주는 것이 좋습니다.


728x90


Consider the following code:

HTML:

<div>
    <label for='name'>Name:</label>
    <input type='text' id='name' />
</div>

CSS:

div {
    height: 50px;
    border: 1px solid blue;
}

What would be the easiest method to put the label and the input in the middle of the div(vertically) ?

shareimprove this question
1 
To my knowledge, the bottom line is "you can't", and the laziest way around it is to use a simple <table>and apply valign='middle' to its <td> s. – BeemerGuy Dec 17 '10 at 0:07 
div {
    display: table-cell;
    vertical-align: middle;
    height: 50px;
    border: 1px solid red;
}

The advantages of this method is that you can change the height of the div, change the height of the text field and change the font size and everything will always stay in the middle.

http://jsfiddle.net/53ALd/6/

shareimprove this answer
1 
looks elegant :) does anyone know how browser compatible this method is? – Zaven Nahapetyan Dec 17 '10 at 0:25
1 
For IE, I think it only works on IE8 or better. For the other web browsers it's fine. – Marc-François Dec 17 '10 at 0:34
1 
I didn't know about the display: table-cell. Is that supported on certain browsers? – BeemerGuy Dec 17 '10 at 0:41
5 
@Misha you should have specified the fact that your input / label were absolutely positioned. That totally changes the circumstances of the question. I am giving Marc a +1. Great answer. – jessegavin Dec 17 '10 at 1:16
2 
I'm fairly certain the point jenson was trying to make (and should have articulated) is that using display: table-cell makes divs behave in ways they aren't expected to behave in, such as subsequent divs rendering on the same line/etc. – taswyn Nov 1 '13 at 20:36

a more modern approach would be to use css flex-box.

div {
  height: 50px;
  background: grey;
  display: flex;
  align-items: center
}
<div>
  <label for='name'>Name:</label>
  <input type='text' id='name' />
</div>

a more complex example... if you have multible elements in the flex flow, you can use align-self to align single elements differently to the specified align...

div {
  display: flex;
  align-items: center
}

* {
  margin: 10px
}

label {
  align-self: flex-start
}
<div>
  <img src="https://de.gravatar.com/userimage/95932142/195b7f5651ad2d4662c3c0e0dccd003b.png?size=50" />
  <label>Text</label>
  <input placholder="Text" type="text" />
</div>

its also super easy to center horizontally and vertically:

div {
  position:absolute;
  top:0;left:0;right:0;bottom:0;
  background: grey;
  display: flex;
  align-items: center;
  justify-content:center
}
<div>
  <label for='name'>Name:</label>
  <input type='text' id='name' />
</div>

shareimprove this answer
   
I wish this would work when there is an image and text wrapped in the label. I have a small icon followed by text, but the text doesn't budge. – Kevin Scharnhorst Mar 9 '17 at 16:20
   
it works if label and text are seperate elements, or if your make your lable a flexbox too... – Holger Will Mar 11 '17 at 16:05 
   
This worked for me! Great examples too! – Tony Dec 5 '17 at 16:44

This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label

label{
     display: block; 
     height: 35px; 
     line-height: 35px; 
     border: 1px solid #000; 
}

input{margin-top:15px; height:20px}

<label for="name">Name: <input type="text" id="name" /></label>
shareimprove this answer
3 
This obviously won't work for a two line label. And if you are sure that label is always single line, than there are millions of other alternatives. – Lashae Apr 18 '13 at 7:33
11 
the question was in regards to a single line label, and i answered accordingly. not sure about your point(s) or intentions here, but if x is so obvious you should go make a million examples of it. at the very least so you can gloat under my answer and feel the power of your million victories. bravo. – albert Apr 18 '13 at 8:23
1 
This is the best answer for single line labels. The specification says: "If the for attribute is not specified, but the label element has a labelable form-associated element descendant, then the first such descendant in tree order is the label element's labeled control." Therefore this is the only approach where you can omit the for and id attributes for maximum simplicity. – parliament Apr 9 '16 at 1:28 

I'm aware this question was asked over two years ago, but for any recent viewers, here's an alternative solution, which has a few advantages over Marc-François's solution:

div {
    height: 50px;
    border: 1px solid blue;
    line-height: 50px;
}

Here we simply only add a line-height equal to that of the height of the div. The advantage being you can now change the display property of the div as you see fit, to inline-block for instance, and it's contents will remain vertically centered. The accepted solution requires you treat the div as a table cell. This should work perfectly, cross-browser.

The only other advantage being it's just one more CSS rule instead of two :)

Cheers!

shareimprove this answer
1 
But won't work if the label text is greater than one line – GlennG Jun 10 '14 at 13:31

Use padding on the div (top and bottom) and vertical-align:middle on the label and input.

example at http://jsfiddle.net/VLFeV/1/

shareimprove this answer
   
That doesn't work on the jsfiddle. I changed the height of the div and the content inside didn't move at all. Am I missing something? – BeemerGuy Dec 17 '10 at 0:39
   
In my opinion, layouts shouldn't have fixed pixel heights… Layouts should flow fluidly around the content. However, I come from a day and time when browsers scaled text sizes when zooming in and out. Recent browsers actually scale the whole page, so setting pixel heights works a little better. However, there are whole new reasons to avoid setting pixel heights… for example, responsive layout techniques. That's why this would be my preferred method. – thirdender Jun 26 '12 at 17:55

Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.

position:absolute; 
top:0; bottom:0; left:0; right:0;
margin:auto;
shareimprove this answer

You can use display: table-cell property as in the following code:

div {
     height: 100%;
     display: table-cell; 
     vertical-align: middle;
    }
shareimprove this answer


'WEB > CSS' 카테고리의 다른 글

[CSS]크로스 브라우징  (0) 2018.01.24
CSS background Property ❮ PreviousComplete CSS Reference Next ❯  (0) 2018.01.24
[CSS]text-indent  (0) 2018.01.18
[CSS] Background Image Size handling  (0) 2018.01.17
CSS Layout - Horizontal & Vertical Align  (0) 2018.01.16

+ Recent posts