In web design, there is a scenario where a series of elements need to be arranged horizontally instead of vertically. For example, when making tables or picture displays, elements often need to be arranged horizontally. At this time, we need to use div css to display without wrapping.
1. Use display:inline-block
We can use the display:inline-block property in CSS to achieve the horizontal arrangement of div elements. After setting the display attribute of the div element to inline-block, the div elements can be arranged in the same order from left to right as text. However, it should be noted that this method requires uniform setting of font-size:0; on the parent element, otherwise gaps will appear in the div element.
Code example:
<style> .parent { font-size: 0; /* 必须设置为0,否则会出现空隙 */ } .child { display: inline-block; width: 100px; height: 100px; background-color: red; margin-right: 10px; } </style> <div class="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div>
2. Use float:left
Another way to achieve div css display without line breaks is to use the float:left attribute. After setting the float attribute of the div element to left, the div elements can be arranged horizontally. However, it should be noted that this method requires clearing the float on the parent element, otherwise the height of the parent element will collapse.
Code example:
<style> .parent { overflow: hidden; /* 清除浮动 */ } .child { float: left; width: 100px; height: 100px; background-color: red; margin-right: 10px; } </style> <div class="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div>
3. Use display:flex
In CSS3, the display:flex attribute is added, which can easily realize the horizontal arrangement of div elements. Set the display attribute of the parent element to flex, and the child elements can be automatically arranged, and the order of the child elements can be adjusted, which is very flexible.
Code example:
<style> .parent { display: flex; } .child { width: 100px; height: 100px; background-color: red; margin-right: 10px; } </style> <div class="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div>
4. Summary
In summary, we can achieve this through display:inline-block, float:left, display:flex and other CSS properties div css does not wrap. Among them, display:inline-block is often used to be compatible with lower version browsers, while float:left is very stable in terms of compatibility. Display:flex is the most popular method and can play a very flexible role in dealing with various complex layouts.
The above is the detailed content of How to prevent div from wrapping in css. For more information, please follow other related articles on the PHP Chinese website!