LoginSignup
6
1

More than 5 years have passed since last update.

0からはじめるelm-ui#4-上下左右中央揃え

Posted at

今日覚えること

centerX, centerYを使って上下左右中央揃えする方法

成果物

image.png

module Main exposing (main)

import Element exposing (..)
import Element.Background as Background


main =
    layout [] <|
        row
            [ Background.color <| rgb255 200 169 85
            , width <| px 400
            , height <| px 400
            ]
            [ column
                [ Background.color <| rgb255 255 169 85
                , width <| px 240
                , height <| px 240
                , centerX
                ]
                [ el [ centerX, centerY ] <| text "Hello, world" ]
            ]

はじめに

#2-stylingで作ったものを覚えていますか?

再掲
image.png

ハロワの文字が左上にありますよね、今日はこれを上下左右中央揃えにしたいと思います

CSSで中央揃えといえばいにしえの時代には大変苦労したらしいですね。わたしは物心ついたころにはflexboxがあったので実際にいろいろやったことはないので分からないのですが

elm-uiではとても簡単に中央揃えできます。2ステップです

コンテナをcolumn(row)にする

元のコードがこれです

el [ Background.color <| rgb255 255 169 85 
   , width <| px 200
   , height <| px 200
   ] 
   <| text "Hello, world."

ハロワの文字列を中央揃えしたいのでそれを囲ってるオレンジの部分をcolumnにします。

column [ Background.color <| rgb255 255 169 85 
   , width <| px 200
   , height <| px 200
   ] 
   [ text "Hello, world." ]

ここまでで下のようになります。見た目は特に変わらないですね

image.png

centerXcenterYを付ける

揃えたい要素にcenterXcenterYを付けます
気を付けてほしいのはコンテナのcolumnのほうではなくハロワのtextのほうに付けるということです

#2-stylingでやったようにtextには直接Attributeをつけれないのでelをつけます

 column
                [ Background.color <| rgb255 255 169 85
                , width <| px 240
                , height <| px 240
                ]
                [ el [ centerX, centerY ] <| text "Hello, world" ]

これでこうなります

image.png

わーい中央揃えできた!今日はもう終わり!

rowでもできるよ

         row
            [ Background.color <| rgb255 200 169 85
            , width <| px 400
            , height <| px 400
            ]
            [ column
                [ Background.color <| rgb255 255 169 85
                , width <| px 240
                , height <| px 240
                , centerX
                ]
                [ el [ centerX, centerY ] <| text "Hello, world" ]
            ]

さらに囲んでみました。できあがりは一番最初に貼った画像です。
内側のオレンジの四角であるcolumncenterXが追加されていますね

rowはデフォルトで上下方向はセンタリングされているのでcenterYを追加する必要はないのです(明記しても問題ありません)

終わりに

  • columnrowで囲んで揃える要素にcenterXなどを付与すると揃います
  • コンテナではなく揃えたい要素自体に属性を追加すること
6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1