The scroll-view component of the applet uses scroll-x + flex layout. The child elements cannot be displayed horizontally.

Problem manifestation

When learning the view and scroll-view components of the mini programscroll-view, set the same style for view and scroll-view, only within the view The child elements of scroll-view can be displayed horizontally, but the child elements within scroll-view are always vertical

<!-- view组件 -->
<view class="container1">
  <view>A</view>
  <view>B</view>
  <view>C</view>
</view>

<!-- scroll-view组件 -->
<scroll-view class="container1 scroll-container-x" scroll-x>
  <view>A</view>
  <view>B</view>
  <view>C</view>
</scroll-view>
.container1{
  display: flex;
  justify-content: space-around;
}
.container1 view{
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}
.container1 view:nth-child(1){
  background-color: lightblue;
}
.container1 view:nth-child(2){
  background-color: lightpink;
}
.container1 view:nth-child(3){
  background-color: lightsalmon;
}

problem causes 

Flex layout in scroll-view component does not take effect

problem solved

Solution 1: Make flex layout take effect by setting properties

Add enable-flex attribute on scroll-view

<scroll-view class="container1 scroll-container-x" scroll-x enable-flex>

When subsequently setting the width of the scroll-view to achieve the scroll-x effect, you will also encounter a problem: when the set scroll-view width is less than the sum of the widths of the sub-elements, the sub-elements will still be displayed vertically. This problem is solved in the following method Speaking of which, jump directly to ➡

Solution 2: Make a hard change and treat it as if the flex layout is not used.

1. The child elements are displayed vertically because the view is a block element and occupies its own line, so the view settingdisplay:inline-block。 can be displayed horizontally

2. In order to achieve the scroll-x effect, set the scroll-view settingswidth:100px。It becomes vertical again

3. Because the width is not enough, it will wrap by default. Add scroll-view.white-space:nowrap 

<!-- view组件 -->
<view class="container1">
  <view>A</view>
  <view>B</view>
  <view>C</view>
</view>

<!-- scroll-view组件 -->
<scroll-view class="container1 scroll-container-x" scroll-x>
  <view>A</view>
  <view>B</view>
  <view>C</view>
</scroll-view>
.container1{
  display: flex;
  justify-content: space-around;
}
.container1 view{
  width: 100px;
  height: 100px;
  display: inline-block;
  text-align: center;
  line-height: 100px;
}
.container1 view:nth-child(1){
  background-color: lightblue;
}
.container1 view:nth-child(2){
  background-color: lightpink;
}
.container1 view:nth-child(3){
  background-color: lightsalmon;
}
.scroll-container-x{
  width: 120px;
  white-space: nowrap;
}

Guess you like

Origin blog.csdn.net/weixin_42017221/article/details/134174649