When using jQuery to layout and design web pages, sometimes we need to center a list element (li tag). Here's how to use jQuery to center a
Method 1: Use flex layout to achieve centering
Flex layout is a new layout method in CSS3, which can quickly achieve centering.
First set the style of the
ul { display: flex; flex-wrap: wrap; justify-content: center; align-items: center; }
At this time, under
Method 2: Use jQuery to calculate the offset and center it
In some cases, we may not be able to use flex layout. In this case, we can use jQuery to calculate the offset so that
First, you need to set the following CSS styles for the
ul { position: relative; } li { position: absolute; left: 50%; transform: translateX(-50%); }
Now, use a piece of jQuery code to calculate the offset required for each
$(window).on('load resize',function(){ var parentWidth = $('ul').width(); // 父元素宽度 $('li').each(function(){ var childWidth = $(this).outerWidth(); // 子元素宽度 var leftOffset = (parentWidth - childWidth) / 2; // 计算偏移量 $(this).css('left', leftOffset + 'px'); // 设置偏移量 }); });
Conclusion
The above are two implementation methods of centering the
The above is the detailed content of jquery sets li tag to center. For more information, please follow other related articles on the PHP Chinese website!